-
Notifications
You must be signed in to change notification settings - Fork 2
/
SequenceManager.ts
1067 lines (895 loc) · 41.2 KB
/
SequenceManager.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {v4 as uuidv4} from 'node-uuid';
const TraceError = require('trace-error');
import CancellationToken from 'cancellationtoken';
import * as jsonpatch from 'json-patch';
import Log from './Log';
import { ExpressApplication, AppContext } from "./ModuleBase";
import { CameraDeviceSettings, BackofficeStatus, SequenceStatus, Sequence, SequenceStep, SequenceStepStatus, SequenceStepParameters, PhdGuideStep, PhdGuideStats, ImageStats, ImageStatus, SequenceValueMonitoring, SequenceValueMonitoringPerClassSettings, SequenceValueMonitoringPerClassStatus} from './shared/BackOfficeStatus';
import JsonProxy from './shared/JsonProxy';
import * as Algebra from './Algebra';
import { hasKey, deepCopy } from './shared/Obj';
import {Task, createTask} from "./Task.js";
import * as GuideStats from "./GuideStats";
import {IdGenerator} from "./IdGenerator";
import * as Obj from "./shared/Obj";
import * as Metrics from "./Metrics";
import * as RequestHandler from "./RequestHandler";
import * as BackOfficeAPI from "./shared/BackOfficeAPI";
import ConfigStore from './ConfigStore';
import { SequenceLogic, Progress } from './shared/SequenceLogic';
import { SequenceActivityWatchdog } from './SequenceActivityWatchdog';
import { SequenceStatisticWatcher } from './SequenceStatisticWatcher';
import { SequenceParamClassifier } from './shared/SequenceParamClassifier';
const logger = Log.logger(__filename);
// export type SequenceStepDefinition = {
// uuid: string;
// repeat?: number;
// dither?: boolean;
// filter?: string|null;
// bin?: number;
// exposure?: number;
// iso?: null|string;
// frameType?: string;
// childs?: SequenceStepDefinition[];
// }
type ScopeState = "light"|"dark"|"flat";
const stateByFrameType :{[id:string]:ScopeState}= {
FRAME_BIAS:"dark",
FRAME_DARK:"dark",
FRAME_FLAT:"flat",
}
const coverMessageByFrameType = {
"light":"Uncover scope",
"dark": "Cover scope",
"flat": "Switch scope to flat field",
}
export default class SequenceManager
implements RequestHandler.APIAppProvider<BackOfficeAPI.SequenceAPI>
{
readonly appStateManager: JsonProxy<BackofficeStatus>;
readonly context: AppContext;
readonly currentStatus: SequenceStatus;
currentSequenceUuid:string|null = null;
currentSequencePromise:Task<void>|null = null;
currentSequenceProgress:Progress|null = null;
sequenceIdGenerator: IdGenerator;
lastFwhm: number|undefined;
lastStarCount: number|undefined;
lastImageTime: number = 0;
lastGuideStats: PhdGuideStats|undefined;
lastBackgroundLevel: number|undefined;
get indiManager() { return this.context.indiManager };
get imagingSetupManager() { return this.context.imagingSetupManager };
get imageProcessor() { return this.context.imageProcessor };
get phd() { return this.context.phd };
constructor(app:ExpressApplication, appStateManager:JsonProxy<BackofficeStatus>, context:AppContext) {
this.appStateManager = appStateManager;
this.appStateManager.getTarget().sequence = {
sequences: {
list: [],
byuuid: {
// Objects with:
// status: 'idle',
// title: 'New sequence',
// camera: null,
// steps: {
// list: [firstSeq],
// byuuid: {
// [firstSeq]: {
// count: 1,
// type: 'FRAME_LIGHT'
// }
// }
//
}
}
}
this.currentStatus = this.appStateManager.getTarget().sequence;
this.context = context;
this.sequenceIdGenerator = new IdGenerator();
new ConfigStore(appStateManager, 'sequences', ['sequence', 'sequences'],
{
list: [],
byuuid: {}
},{
list: [],
byuuid: {}
},
// read callback
(content:SequenceStatus["sequences"])=> {
// Renumber sequences
this.sequenceIdGenerator.renumber(content.list, content.byuuid);
for(const sid of Object.keys(content.byuuid)) {
const seq = this.completeSequence(content.byuuid[sid]);
content.byuuid[sid] =seq;
seq.images = [];
if (!seq.imageStats) {
seq.imageStats = {};
}
if (seq.storedImages) {
for(const image of seq.storedImages!) {
const {device, path, ...stats} = {...image};
const status: ImageStatus = {device, path};
// Pour l'instant c'est brutal
const uuid = this.context.camera.imageIdGenerator.next();
this.context.camera.currentStatus.images.list.push(uuid);
this.context.camera.currentStatus.images.byuuid[uuid] = status;
seq.images.push(uuid);
seq.imageStats[uuid] = stats;
}
}
delete(seq.storedImages);
}
return content;
},
// write callback (add new images)
(content:SequenceStatus["sequences"])=>{
content = deepCopy(content);
const arrivalTime = new Date().getTime();
for(const sid of Object.keys(content.byuuid)) {
const seq = content.byuuid[sid];
seq.storedImages = [];
for(const uuid of seq.images || []) {
if (hasKey(this.context.camera.currentStatus.images.byuuid, uuid)) {
const toWrite = {
arrivalTime,
...this.context.camera.currentStatus.images.byuuid[uuid],
... Obj.getOwnProp(seq.imageStats, uuid)};
seq.storedImages.push(toWrite);
}
}
delete seq.images;
delete seq.imageStats;
}
return content;
}
);
// Ensure no sequence is running on start
this.pauseRunningSequences();
}
private completeSequence=(t:Partial<Sequence>): Sequence=>{
const defaultSequence:Sequence = {
activityMonitoring: {
enabled: false
},
backgroundMonitoring: {
enabled: false,
evaluationCount: 5,
evaluationPercentile: 0.5,
learningCount: 5,
learningPercentile: 0.5,
perClassSettings:{},
perClassStatus:{},
},
fwhmMonitoring: {
enabled: false,
evaluationCount: 5,
evaluationPercentile: 0.5,
learningCount: 5,
learningPercentile: 0.5,
perClassSettings:{},
perClassStatus:{},
},
imageStats: {},
images: [],
imagingSetup: null,
progress: null,
root: {},
status: 'error',
errorMessage: 'Convertion error',
stepStatus: {},
title: 'invalid sequence',
}
return {...defaultSequence, ...t};
}
newSequence=async (ct: CancellationToken, message: {}):Promise<string>=>{
const key = uuidv4();
const firstSeq = uuidv4();
// FIXME: takes parameters from the last created sequence
this.currentStatus.sequences.byuuid[key] = this.completeSequence({
status: 'idle',
title: 'New sequence',
progress: null,
imagingSetup: null,
errorMessage: null,
root: {
type: 'FRAME_LIGHT'
},
images: [],
imageStats: {},
});
this.currentStatus.sequences.list.push(key);
return key;
}
findSequenceFromRequest=(sequenceUid:string): Sequence=>
{
if (!hasKey(this.currentStatus.sequences.byuuid, sequenceUid)) {
throw new Error("Sequence not found");
}
return this.currentStatus.sequences.byuuid[sequenceUid];
}
findStepFromRequest=(message: {sequenceUid:string, stepUidPath: string[]}): SequenceStep=>
{
const seq = this.findSequenceFromRequest(message.sequenceUid);
let ret = seq.root;
for(const childUuid of message.stepUidPath) {
if ((!ret.childs) || !hasKey(ret.childs.byuuid, childUuid)) {
throw new Error("Sequence step not found");
}
ret = ret.childs.byuuid[childUuid];
}
return ret;
}
newSequenceStep=async (ct: CancellationToken, message:BackOfficeAPI.NewSequenceStepRequest)=>{
const parentStep = this.findStepFromRequest(message);
if (!parentStep.childs) {
parentStep.childs = {
byuuid:{},
list: [],
};
}
if (message.removeParameterFromParent) {
delete parentStep[message.removeParameterFromParent];
}
const ret: string[] = [];
for(let i = 0; i < Math.max(1, message.count||0); ++i)
{
const sequenceStepUid = uuidv4();
const newStep: SequenceStep = {
};
parentStep.childs.list.push(sequenceStepUid);
parentStep.childs.byuuid[sequenceStepUid] = newStep;
ret.push(sequenceStepUid);
}
return ret;
}
moveSequenceSteps=async (ct: CancellationToken, message:BackOfficeAPI.MoveSequenceStepsRequest)=>{
const parentStep = this.findStepFromRequest(message);
if (!parentStep.childs) {
throw new Error("Sequence has no childs");
}
for(const o of message.childs) {
if (!hasKey(parentStep.childs.byuuid, o)) {
throw new Error("Unknown child");
}
}
const newSet = new Set(message.childs);
if (newSet.size !== message.childs.length) {
throw new Error("Duplicated child");
}
for(const o of parentStep.childs.list) {
if (!newSet.has(o)) {
throw new Error("missing child");
}
}
parentStep.childs.list = message.childs;
}
pauseRunningSequences()
{
for(var k of Object.keys(this.currentStatus.sequences.byuuid))
{
var seq = this.currentStatus.sequences.byuuid[k];
if (seq.status == "running") {
logger.warn('Sequence interrupted by process death', {uuid: k, seq});
seq.status ="paused";
}
}
}
public deleteSequenceStep = async(ct: CancellationToken, message:BackOfficeAPI.DeleteSequenceStepRequest)=>{
const parentStep = this.findStepFromRequest(message);
// FIXME: not for running step ?
if ((!parentStep.childs) || !hasKey(parentStep.childs.byuuid, message.stepUid)) {
throw new Error("Step not found");
}
delete parentStep.childs.byuuid[message.stepUid];
let p;
while ((p=parentStep.childs.list.indexOf(message.stepUid)) != -1) {
parentStep.childs.list.splice(p, 1);
}
if (parentStep.childs.list.length === 0) {
delete parentStep.childs;
}
}
public updateSequence = async (ct: CancellationToken, message:BackOfficeAPI.UpdateSequenceRequest)=>{
const seq = this.findSequenceFromRequest(message.sequenceUid);
const param = message.param;
const value = message.value;
(seq as any)[param] = value;
}
public patchSequence = async (ct: CancellationToken, message: BackOfficeAPI.PatchSequenceRequest) => {
const seq = this.findSequenceFromRequest(message.sequenceUid);
const newSeq = deepCopy(JsonProxy.applyDiff(seq, message.patch));
SequenceManager.syncOnUpdate(seq, newSeq);
this.currentStatus.sequences.byuuid[message.sequenceUid] = newSeq;
}
// Adjust to sane values after update
static syncOnUpdate(src: Sequence, dst: Sequence) {
if (!Obj.deepEqual(src.activityMonitoring, dst.activityMonitoring)) {
if (dst.activityMonitoring.enabled) {
if ((dst.activityMonitoring.duration || -1 ) < 0 ) {
dst.activityMonitoring.duration = 300;
}
}
}
SequenceManager.syncStatMonitoring(src.fwhmMonitoring, dst.fwhmMonitoring);
SequenceManager.syncStatMonitoring(src.backgroundMonitoring, dst.backgroundMonitoring);
}
static syncStatMonitoring(src: SequenceValueMonitoring, dst: SequenceValueMonitoring) {
if (Obj.deepEqual(src, dst)) {
return;
}
if (src.seuil && src.seuil < 0) {
dst.seuil = undefined;
}
for(const jsc of Object.keys(dst.perClassStatus)) {
const dstClassStatus = dst.perClassStatus[jsc];
if (!Object.prototype.hasOwnProperty.call(src?.perClassStatus, jsc)) {
dst.perClassStatus[jsc] = {
...SequenceLogic.emptyMonitoringClassStatus,
...dstClassStatus
};
}
}
}
public resetStatMonitoringLearning = async(ct: CancellationToken, message: BackOfficeAPI.ResetStatMonitoringRequest)=> {
const seq = this.findSequenceFromRequest(message.sequenceUid);
const monitoring = seq[message.monitoring];
const classSettings = Obj.getOwnProp(monitoring.perClassSettings, message.classId);
if (classSettings !== undefined) {
classSettings.learningMinTime = new Date().getTime();
}
const classStatus = Obj.getOwnProp(monitoring.perClassStatus, message.classId);
if (classStatus !== undefined) {
classStatus.learnedValue = null;
classStatus.learnedCount = 0;
classStatus.learningReady = false;
if ((!classSettings?.disable) && (classSettings?.manualValue === undefined)) {
classStatus.maxAllowedValue = null;
}
}
}
public resetStatMonitoringCurrent = async(ct: CancellationToken, message: BackOfficeAPI.ResetStatMonitoringRequest)=> {
const seq = this.findSequenceFromRequest(message.sequenceUid);
const monitoring = seq[message.monitoring];
if (Obj.hasKey(monitoring.perClassSettings, message.classId)) {
monitoring.perClassSettings[message.classId].evaluationMinTime = new Date().getTime();
}
if (Obj.hasKey(monitoring.perClassStatus, message.classId)) {
seq[message.monitoring].perClassStatus[message.classId].currentValue = null;
seq[message.monitoring].perClassStatus[message.classId].currentCount = 0;
}
}
public patchSequenceStep = async (ct: CancellationToken, message:BackOfficeAPI.PatchSequenceStepRequest)=>{
const parentStep = this.findStepFromRequest(message);
jsonpatch.apply(parentStep, message.patch);
}
public updateSequenceStep = async (ct: CancellationToken, message:BackOfficeAPI.UpdateSequenceStepRequest)=>{
const parentStep = this.findStepFromRequest(message);
const param = message.param;
const value = message.value;
if (value === undefined) {
delete (parentStep as any)[param];
} else {
(parentStep as any)[param] = value;
}
}
public updateSequenceStepFocuser = async (ct: CancellationToken, message:BackOfficeAPI.UpdateSequenceStepFocuserRequest)=>{
const parentStep = this.findStepFromRequest(message);
const wanted = message.focuser;
if (!wanted) {
parentStep.focuser = null;
} else {
if (!parentStep.focuser) {
// FIXME: recall default settings here
parentStep.focuser = {...{}, once: false}
}
if (message.settings) {
const s = message.settings;
Object.assign(parentStep.focuser, message.settings);
// FIXME: retain default settings ?
}
}
}
public updateSequenceStepDithering = async (ct: CancellationToken, message:BackOfficeAPI.UpdateSequenceStepDitheringRequest)=>{
const parentStep = this.findStepFromRequest(message);
const wanted = message.dithering;
if (!wanted) {
parentStep.dithering = null;
} else {
if (!parentStep.dithering) {
parentStep.dithering = {...this.context.phd.currentStatus.configuration.preferredDithering, once: false}
}
if (message.settings) {
const s = message.settings;
if (s.amount !== undefined && (s.amount <= 0 || s.amount > 100)) {
throw new Error("invalid value for amount");
}
if (s.pixels !== undefined && (s.pixels <= 0 || s.pixels > 100)) {
throw new Error("invalid value for pixels");
}
if (s.time !== undefined && (s.time <= 0 || s.time > 1000)) {
throw new Error("invalid value for time");
}
if (s.timeout !== undefined && (s.timeout <= 0 || s.timeout > 1000)) {
throw new Error("invalid value for time");
}
Object.assign(parentStep.dithering, message.settings);
// Retains as the new default values
this.context.phd.currentStatus.configuration.preferredDithering = {...parentStep.dithering};
}
}
}
private needCoverScopeMessage(cameraId:string) {
const devConf = this.indiManager.currentStatus.configuration.indiServer.devices;
if (!hasKey(devConf, cameraId)) {
return false;
}
return !devConf[cameraId].options.disableAskCoverScope;
}
private disableCoverScopeMessage(cameraId: string) {
const devConf = this.indiManager.currentStatus.configuration.indiServer.devices;
try {
this.indiManager.doUpdateDriverParam({driver: cameraId, key: "disableAskCoverScope", value: true});
this.context.notification.info("Cover scope message can be enabled in INDI tab");
} catch(e) {
this.context.notification.error("Unable to control cover scope message preference", e);
}
}
private doStartSequence = async (ct: CancellationToken, uuid:string)=>{
const getSequence=()=>{
var rslt = this.currentStatus.sequences.byuuid[uuid];
if (!rslt) {
throw new Error("Sequence removed: " + uuid);
}
return rslt;
}
const computeStats = async (ct: CancellationToken, indiFrameType: string|undefined, shootResult: BackOfficeAPI.ShootResult, target: ImageStats, guideSteps: Array<PhdGuideStep>)=> {
ct.throwIfCancelled();
target.guideStats = GuideStats.computeGuideStats(guideSteps);
const histogram = await this.imageProcessor.compute(ct,
{
histogram: { source: {
path: shootResult.path,
streamId: "",
},
options: {
maxBits: 10
}
},
});
const channelBlacks = histogram.map(ch=>this.imageProcessor.getHistgramAduLevel(ch, 0.2));
target.backgroundLevel = channelBlacks.length ? channelBlacks.reduce((a, c)=>a+c, 0) / (1024 * channelBlacks.length) : undefined;
if (indiFrameType === 'FRAME_LIGHT') {
ct.throwIfCancelled();
// FIXME: mutualise that somewhere
logger.debug('Asking FWHM', {shootResult});
const starFieldResponse = await this.imageProcessor.compute(ct, {
starField: { source: {
path: shootResult.path,
streamId: "",
}}
});
const starField = starFieldResponse.stars;
logger.debug('Got starField', {shootResult, starField});
let fwhm, starCount;
starCount = starField.length;
fwhm = Algebra.starFieldFwhm(starField);
if (isNaN(fwhm)) fwhm = undefined;
if (fwhm === undefined) {
delete target.fwhm;
} else {
target.fwhm = fwhm;
}
target.starCount = starCount;
logger.info('Got FWHM', {shootResult, fwhm, starCount});
}
}
const computeStatsWithMetrics = async (ct: CancellationToken, indiFrameType: string|undefined, shootResult: BackOfficeAPI.ShootResult, target: ImageStats, guideSteps: Array<PhdGuideStep>)=>{
// FIXME :report error here
await computeStats(ct, indiFrameType, shootResult, target, guideSteps);
this.lastImageTime = Date.now();
this.lastGuideStats = Obj.deepCopy(target.guideStats);
this.lastBackgroundLevel = target.backgroundLevel;
this.lastFwhm = target.fwhm;
this.lastStarCount = target.starCount;
logger.debug('Statistic updated', target);
}
const sequenceLogic = async (ct: CancellationToken) => {
let scopeState: ScopeState = "light";
const sequenceActivityWatchdog = new SequenceActivityWatchdog(this.appStateManager, this.context, uuid);
const sequenceFwhmWatcher = new SequenceStatisticWatcher(this.appStateManager, this.context, uuid, "fwhm", "fwhmMonitoring");
const sequenceBackgroundWatcher = new SequenceStatisticWatcher(this.appStateManager, this.context, uuid, "backgroundLevel", "backgroundMonitoring");
try {
sequenceActivityWatchdog.reset(0);
sequenceFwhmWatcher.start();
sequenceBackgroundWatcher.start();
while(true) {
ct.throwIfCancelled();
const sequence = getSequence();
const sequenceLogic = new SequenceLogic(sequence, uuidv4);
sequence.progress = null;
const nextStep = sequenceLogic.getNextStep();
if (nextStep === undefined) {
logger.info('Sequence terminated', {sequence, uuid});
return;
}
// const {stepId, step} = nextStep;
if (sequence.imagingSetup === null) {
throw new Error("No imaging setup specified");
}
const imagingSetupInstance = ()=> {
const isi = this.imagingSetupManager.getImagingSetupInstance(sequence.imagingSetup);
if (!isi.exists()) {
throw new Error("Unknown imaging setup");
}
return isi;
}
const cameraDevice = () => {
const isi = imagingSetupInstance();
const ret = isi.config().cameraDevice;
if (ret === null) {
throw new Error("Imaging setup has no camera");
}
return ret;
}
const filterWheelDevice = () => {
const isi = imagingSetupInstance();
const ret = isi.config().filterWheelDevice;
if (ret === null) {
throw new Error("Imaging setup has no filter wheel");
}
return ret;
}
// Check that camera is connected
const device = this.indiManager.checkDeviceConnected(cameraDevice());
const param : SequenceStep = sequenceLogic.getParameters(nextStep);
// Get the name of frame type
const stepTypeLabel =
(param.type ? device.getVector('CCD_FRAME_TYPE').getPropertyLabelIfExists(param.type) : undefined)
|| 'image';
const progress = sequenceLogic.getProgress(nextStep);
this.currentSequenceProgress = progress;
{
const classifier = new SequenceParamClassifier();
sequenceLogic.scanParameters(classifier.addParameter);
sequence.currentImageClass = classifier.extractJcsIdForParameters(param);
}
const shootTitle = (progress.imagePosition + 1) + "/" + progress.totalCount
+ (progress.totalTime > 0
? (" " + Math.round(100 * progress.timeSpent / progress.totalTime) + "%")
: ""
);
if (!param.exposure) {
throw new Error("Exposure not specified for " + shootTitle);
}
const settings:CameraDeviceSettings = {...param, exposure: param.exposure};
settings.prefix = sanitizePath(sequence.title) + '_' + sanitizePath(stepTypeLabel);
if (param.filter) {
settings.prefix += '_' + sanitizePath(param.filter);
}
if (param.exposure < 1 || (param.exposure % 1)) {
settings.prefix += '_' + Math.floor(param.exposure * 1000) + 'ms';
} else {
settings.prefix += '_' + Math.floor(param.exposure) + 's';
}
settings.prefix += '_XXX';
const currentExecutionStatus = nextStep[nextStep.length - 1];
// Copy because it could change concurrently in case of removal/reorder
const currentExecutionUuid = currentExecutionStatus.status.execUuid;
if (param.dithering
&& nextStep[nextStep.length - 1].status.lastDitheredExecUuid != nextStep[nextStep.length - 1].status.execUuid) {
// FIXME: no dithering for first shoot of sequence
logger.info('Dithering required', {sequence, uuid, dithering: param.dithering});
sequence.progress = "Dither " + shootTitle;
await this.context.phd.dither(ct, param.dithering);
// Mark the dithering as done
currentExecutionStatus.status.lastDitheredExecUuid = currentExecutionUuid;
ct.throwIfCancelled();
continue;
}
// Send a cover scope dialog if required
const newScopeState:ScopeState = (param.type && hasKey(stateByFrameType, param.type)) ? stateByFrameType[param.type] : 'light';
if (newScopeState !== scopeState) {
if (this.needCoverScopeMessage(cameraDevice()))
{
// Check that camera is connected first
this.indiManager.checkDeviceConnected(cameraDevice());
// Ask confirmation
const acked = await this.context.notification.dialog<boolean|"neverask">(ct, coverMessageByFrameType[newScopeState],
[{title:"Ok", value: true}, {title:"Pause Seq", value: false}, {title:"Never ask", value: "neverask"}]);
if (!acked) {
throw new CancellationToken.CancellationError("User canceled");
}
if (acked === "neverask") {
this.disableCoverScopeMessage(cameraDevice());
}
}
scopeState = newScopeState;
}
let guiderInhibiter = this.context.phd.createInhibiter();
try {
if (param.filter) {
console.log('Setting filter to ' + param.filter);
sequence.progress = "Filter " + shootTitle;
const filterWheelDeviceId = filterWheelDevice();
if (filterWheelDeviceId === null) {
throw new Error("Imaging setup has no filter wheel");
}
this.indiManager.checkDeviceConnected(filterWheelDeviceId);
await this.context.filterWheel.changeFilter(ct, {
filterWheelDeviceId,
filterId: param.filter,
});
ct.throwIfCancelled();
}
if (param.focuser) {
let delta;
try {
delta = this.context.focuser.getFocuserDelta(sequence.imagingSetup || "invalid");
} catch(e) {
if (e instanceof Error) {
throw new Error("Focuser: "+ e.message);
}
throw e;
}
logger.debug('Got focuser delta', {sequence, uuid, delta});
if (delta.fromCurWeight >= 1) {
logger.info('Focuser needs adjustment', {sequence, uuid, delta});
sequence.progress = "Adjusting focuser " + shootTitle + " (" + Math.round(delta.fromCur) +")";
if (this.context.focuser.needGuideInhibition(sequence.imagingSetup || "invalid")) {
await guiderInhibiter.start(ct);
}
await this.context.focuser.moveFocuserWithBacklash(ct, sequence.imagingSetup || "invalid", delta.abs);
logger.info('Focuser adjustment done', {sequence, uuid});
ct.throwIfCancelled();
} else {
logger.info('Focuser is good enough', {sequence, uuid, delta});
}
}
} finally {
await guiderInhibiter.end(ct);
}
// FIXME : wait end of guiding to settle ?
sequence.progress = (stepTypeLabel) + " " + shootTitle;
ct.throwIfCancelled();
const guideSteps:Array<PhdGuideStep> = [];
const unregisterPhd = (param.type === 'FRAME_LIGHT') ? this.phd.listenForSteps((step)=>guideSteps.push(step)) : ()=>{};
logger.info('Starting exposure', {sequence, uuid, settings});
let shootResult;
try {
sequenceActivityWatchdog.reset(-settings.exposure);
shootResult = await this.context.camera.doShoot(ct, sequence.imagingSetup, ()=>(settings));
} finally {
unregisterPhd();
}
progress.imagePosition++;
progress.timeSpent += param.exposure;
sequence.images.push(shootResult.uuid);
sequenceLogic.finish(currentExecutionStatus);
sequence.imageStats[shootResult.uuid] = Obj.noUndef({
arrivalTime: new Date().getTime(),
exposure: settings.exposure,
iso: param.iso,
type: param.type,
bin: param.bin,
filter: param.filter,
});
computeStatsWithMetrics(CancellationToken.CONTINUE, param.type, shootResult, sequence.imageStats[shootResult.uuid], guideSteps)
.finally(sequenceFwhmWatcher.updateStats)
.finally(sequenceBackgroundWatcher.updateStats);
}
} finally {
sequenceActivityWatchdog.end();
sequenceFwhmWatcher.end();
sequenceBackgroundWatcher.end();
}
}
const finishWithStatus = (s:'done'|'error'|'paused', e?:any)=>{
if (e) {
logger.error('Finish sequence', {uuid, status:s}, e);
} else {
logger.info('Finish sequence', {uuid, status:s});
}
var seq = this.currentStatus.sequences.byuuid[uuid];
seq.status = s;
if (e) {
if (e instanceof TraceError) {
seq.errorMessage = "" + e.messages();
} else if (e instanceof Error) {
seq.errorMessage = e.message;
} else {
seq.errorMessage = "" + e;
}
} else {
seq.errorMessage = null;
}
if (s === 'done') {
delete seq.currentImageClass;
}
this.currentSequenceUuid = null;
this.currentSequencePromise = null;
if (s !== "paused") {
this.context.notification.notify("Sequence " + seq.title + " " + s + (e ? ": " + e : ""));
}
}
// Check no sequence is running ?
if (this.currentSequencePromise !== null) {
throw new Error("A sequence is already running");
}
if (!Obj.hasKey(this.currentStatus.sequences.byuuid, uuid)) {
throw new Error("No sequence");
}
await (createTask(ct, async (task:Task<void>)=> {
this.currentSequencePromise = task;
this.currentSequenceProgress = null;
this.currentSequenceUuid = uuid;
this.currentStatus.sequences.byuuid[uuid].status = 'running';
this.currentStatus.sequences.byuuid[uuid].errorMessage = null;
try {
task.cancellation.throwIfCancelled();
await sequenceLogic(task.cancellation);
} catch(e) {
if (e instanceof CancellationToken.CancellationError) {
finishWithStatus('paused');
} else {
finishWithStatus('error', e)
}
throw e;
}
finishWithStatus('done');
}));
}
startSequence = async (ct: CancellationToken, message:{sequenceUid: string})=>{
this.doStartSequence(ct, message.sequenceUid);
}
stopSequence = async (ct: CancellationToken, message:{sequenceUid: string})=>{
if (this.currentSequenceUuid !== message.sequenceUid) {
throw new Error("Sequence " + message.sequenceUid + " is not running");
}
this.currentSequencePromise!.cancel();
}
resetSequence = async (ct: CancellationToken, message:{sequenceUid: string})=>{
const key = message.sequenceUid;
if (this.currentSequenceUuid === key) {
throw new Error("Sequence " + key + " is running");
}
if (!Object.prototype.hasOwnProperty.call(this.currentStatus.sequences.byuuid, key)) {
throw new Error("Sequence " + key + " not found");
}
const sequence = this.currentStatus.sequences.byuuid[key];
sequence.stepStatus = {};
sequence.status = 'idle';
sequence.progress = null;
sequence.errorMessage = null;
// for(const stepUuid of sequence.steps.list)
// {
// const step = sequence.steps.byuuid[stepUuid];
// delete step.done;
// }
}
dropSequence = async (ct: CancellationToken, message:{sequenceUid: string})=>{
const key = message.sequenceUid;
if (this.currentSequenceUuid === key) {
throw new Error("Sequence " + key + " is running");
}
let i;
while((i = this.currentStatus.sequences.list.indexOf(key)) != -1) {
this.currentStatus.sequences.list.splice(i, 1);
}
delete(this.currentStatus.sequences.byuuid[key]);
}
public async metrics():Promise<Array<Metrics.Definition>> {
let ret : Array<Metrics.Definition> = [];
const alive = Date.now() - this.lastImageTime < 60000;
ret.push({
name: 'sequence_fwhm',
help: 'last fwhm of LIGHT image from sequence',
type: 'gauge',
value: alive ? this.lastFwhm : undefined,
});
ret.push({
name: 'sequence_background_level',
help: 'adu level (0-1) of black (20% histogram) - of last LIGHT image from sequence',
type: 'gauge',
value: alive ? this.lastBackgroundLevel: undefined,
});
ret.push({
name: 'sequence_guiding_rms',
help: 'rms error for the last LIGHT image from sequence',
type: 'gauge',
value: alive ? nullToUndefined(this.lastGuideStats?.RADECDistanceRMS) : undefined,
});
ret.push({
name: 'sequence_guiding_rms_ra',
help: 'rms error (ra) for the last LIGHT image from sequence',
type: 'gauge',
value: alive ? nullToUndefined(this.lastGuideStats?.RADistanceRMS) : undefined,
});
ret.push({
name: 'sequence_guiding_rms_dec',
help: 'rms error (dec) for the last LIGHT image from sequence',
type: 'gauge',
value: alive ? nullToUndefined(this.lastGuideStats?.DECDistanceRMS) : undefined,
});
ret.push({
name: 'sequence_guiding_peak',
help: 'peak error for the last LIGHT image from sequence',
type: 'gauge',
value: alive ? nullToUndefined(this.lastGuideStats?.RADECDistancePeak) : undefined,
});
ret.push({
name: 'sequence_guiding_peak_ra',
help: 'peak error (ra) for the last LIGHT image from sequence',
type: 'gauge',
value: alive ? nullToUndefined(this.lastGuideStats?.RADistancePeak) : undefined,
});
ret.push({
name: 'sequence_guiding_peak_dec',
help: 'rms error (peak) for the last LIGHT image from sequence',
type: 'gauge',
value: alive ? nullToUndefined(this.lastGuideStats?.DECDistancePeak) : undefined,
});
ret.push({
name: 'sequence_star_count',
help: 'number of stars detected in LIGHT image from sequence',
type: 'gauge',
value: alive ? this.lastStarCount : undefined,
});