-
Notifications
You must be signed in to change notification settings - Fork 2
/
Focuser.ts
664 lines (585 loc) · 25.5 KB
/
Focuser.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
const PolynomialRegression = require('ml-regression-polynomial');
import CancellationToken from 'cancellationtoken';
import Log from './Log';
import { hasKey } from './shared/Obj';
import * as AccessPath from './shared/AccessPath';
import * as Algebra from './Algebra';
import * as BackOfficeAPI from './shared/BackOfficeAPI';
import * as FocuserDelta from './FocuserDelta';
import * as RequestHandler from './RequestHandler';
import { ExpressApplication, AppContext } from "./ModuleBase";
import ConfigStore from './ConfigStore';
import JsonProxy from './shared/JsonProxy';
import { BackofficeStatus, AutoFocusStatus, FocuserStatus, FocuserUpdateCurrentSettingsRequest, CameraStatus, FocuserSettings, AutoFocusConfiguration, IndiPropertyIdentifier } from './shared/BackOfficeStatus';
import { Task, createTask } from './Task';
import Camera from './Camera';
import IndiManager from "./IndiManager";
import {ImagingSetupInstance} from "./ImagingSetupManager";
import ImageProcessor from "./ImageProcessor";
import IndirectionSynchronizer from './IndirectionSynchronizer';
import { PhdGuideInhibiter } from './Phd';
const logger = Log.logger(__filename);
export default class Focuser implements RequestHandler.APIAppImplementor<BackOfficeAPI.FocuserAPI>{
readonly appStateManager: JsonProxy<BackofficeStatus>;
readonly currentStatus: FocuserStatus;
currentPromise: Task<number>|null;
camera: Camera;
indiManager: IndiManager;
imageProcessor: ImageProcessor;
context: AppContext;
constructor(app:ExpressApplication, appStateManager:JsonProxy<BackofficeStatus>, context:AppContext)
{
this.context = context;
this.appStateManager = appStateManager;
this.appStateManager.getTarget().focuser = {
currentImagingSetup: null,
config: {
preferedImagingSetup: null,
},
current: {
status: 'idle',
error: null,
imagingSetup: null,
// position => details
firstStep: 0,
lastStep: 10000,
points: {
"5000": {
fwhm: 2.9
},
"6000": {
fwhm: 2.7
},
"7000": {
fwhm: 2.5
},
"8000": {
fwhm: 2.6
},
"9000": {
fwhm: 2.8
}
},
predicted: {
},
targetStep: 3000
}
};
this.currentStatus = this.appStateManager.getTarget().focuser;
new ConfigStore<AutoFocusConfiguration>(appStateManager, 'focuser', ['focuser', 'config'], {
preferedImagingSetup: null,
}, {
preferedImagingSetup: null,
});
this.currentPromise = null;
this.resetCurrent('idle');
this.camera = context.camera;
this.indiManager = context.indiManager;
this.imageProcessor = context.imageProcessor;
context.imagingSetupManager.createPreferredImagingSelector({
currentPath: [ 'focuser', 'currentImagingSetup' ],
preferedPath: [ 'focuser', 'config', 'preferedImagingSetup' ],
read: ()=> ({
prefered: this.currentStatus.config.preferedImagingSetup,
current: this.currentStatus.currentImagingSetup,
}),
set: (s:{prefered?: string|null|undefined, current?: string|null|undefined})=>{
if (s.prefered !== undefined) {
this.currentStatus.config.preferedImagingSetup = s.prefered;
}
if (s.current !== undefined) {
this.currentStatus.currentImagingSetup = s.current;
}
}
});
// Report the focuser temperature
new IndirectionSynchronizer<BackofficeStatus, null|IndiPropertyIdentifier>(
this.appStateManager,
AccessPath.ForWildcard((e, ids)=>e.imagingSetup.configuration.byuuid[ids[0]].focuserSettings.temperatureProperty),
(imagingSetupUuid: string, propertyIdentifier: null|IndiPropertyIdentifier)=> {
this.refreshFocuserTemperature(imagingSetupUuid);
if (propertyIdentifier !== null) {
return this.appStateManager.addTypedSynchronizer(
AccessPath.For((e)=>e.indiManager.deviceTree[propertyIdentifier.device][propertyIdentifier.vector]),
()=> this.refreshFocuserTemperature(imagingSetupUuid),
false
)
} else {
return null;
}
}
);
// Report the focuser position
new IndirectionSynchronizer<BackofficeStatus, null|string>(
this.appStateManager,
AccessPath.ForWildcard((e, ids)=>e.imagingSetup.configuration.byuuid[ids[0]].focuserDevice),
(imagingSetupUuid: string, focuserDevice: null|string)=> {
this.refreshFocuserPosition(imagingSetupUuid);
if (focuserDevice !== null) {
return this.appStateManager.addTypedSynchronizer(
AccessPath.For((e)=>e.indiManager.deviceTree[focuserDevice]['ABS_FOCUS_POSITION']),
()=> this.refreshFocuserPosition(imagingSetupUuid),
false
)
} else {
return null;
}
}
);
// Report the filterwheel position
for(const w of ['FILTER_SLOT', 'FILTER_NAME']) {
const watchedVec = w;
new IndirectionSynchronizer<BackofficeStatus, null|string>(
this.appStateManager,
AccessPath.ForWildcard((e, ids)=>e.imagingSetup.configuration.byuuid[ids[0]].filterWheelDevice),
(imagingSetupUuid: string, filterWheelDevice: null|string)=> {
this.refreshFocuserFilter(imagingSetupUuid);
if (filterWheelDevice !== null) {
return this.appStateManager.addTypedSynchronizer(
AccessPath.For((e)=>e.indiManager.deviceTree[filterWheelDevice][watchedVec]),
()=> this.refreshFocuserFilter(imagingSetupUuid),
false
)
} else {
return null;
}
}
);
}
}
public moveFocuserWithBacklash = async (ct: CancellationToken, imagingSetupUuid: string, target: number):Promise<void>=>{
const config = this.context.imagingSetupManager.getImagingSetupInstance(imagingSetupUuid).config();
if (config.focuserDevice === null) {
throw new Error("No focuser declared in imagingSetup");
}
const focuserId = config.focuserDevice;
target = Math.round(target);
const connection = this.indiManager.getValidConnection();
// check device connected
const focuser = connection.getDevice(focuserId);
if (!focuser.isConnected()) {
logger.warn("Focuser not connected");
throw new Error("Focuser not connected");
}
// Move to the starting point
const absPos = focuser.getVector('ABS_FOCUS_POSITION');
if (!absPos.isReadyForOrder()) {
logger.warn("Focuser not ready");
throw new Error("Focuser is not ready");
}
const moveForward = config.focuserSettings.lowestFirst;
let currentPos:number = parseFloat(absPos.getPropertyValue("FOCUS_ABSOLUTE_POSITION"));
const backlash = config.focuserSettings.backlash;
let intermediate = undefined;
if (backlash != 0) {
if (moveForward) {
// Need backlash clearance in this direction
if (target < currentPos) {
intermediate = target - backlash;
}
} else {
if (target > currentPos) {
intermediate = target + backlash;
}
}
if (intermediate !== undefined && intermediate < 0) {
intermediate = 0;
}
// FIXME: check upper bound
}
if ((intermediate !== undefined) && (intermediate !== target)) {
// Account for backlash
logger.info('Clearing backlash', {intermediate, target});
await this.rawMoveFocuser(ct, focuserId, intermediate);
}
// Direct move
logger.info('Moving focuser', {target});
await this.rawMoveFocuser(ct, focuserId, target);
}
refreshFocuserPosition(imagingSetupUid: string)
{
const instance = this.context.imagingSetupManager.getImagingSetupInstance(imagingSetupUid);
if (!instance.exists()) {
return;
}
const imagingSetup = instance.config();
let value;
const focuserDevice = imagingSetup.focuserDevice;
if (focuserDevice !== null) {
value = this.indiManager.getNumberPropertyValue(focuserDevice, 'ABS_FOCUS_POSITION', 'FOCUS_ABSOLUTE_POSITION');
} else {
value = { value: null, warning: null };
}
if (imagingSetup.dynState.focuserWarning !== value.warning
|| imagingSetup.dynState.curFocus?.position !== (value.value !== null ? value.value : undefined)) {
logger.info("Updated focuser position to ", {imagingSetupUid, value});
imagingSetup.dynState.focuserWarning = value.warning;
if (value.value === null) {
imagingSetup.dynState.curFocus = null;
} else {
if (imagingSetup.dynState.curFocus === null) {
imagingSetup.dynState.curFocus = {
filter: null,
temp: null,
position: value.value
}
// When creating, force values for other parts
this.refreshFocuserTemperature(imagingSetupUid);
this.refreshFocuserFilter(imagingSetupUid);
} else {
imagingSetup.dynState.curFocus.position = value.value;
}
}
}
}
refreshFocuserTemperature(imagingSetupUid: string)
{
const instance = this.context.imagingSetupManager.getImagingSetupInstance(imagingSetupUid);
if (!instance.exists()) {
return;
}
const imagingSetup = instance.config();
if (imagingSetup.dynState.curFocus === null) {
imagingSetup.dynState.temperatureWarning = null;
return;
}
let value;
const tempProp = imagingSetup.focuserSettings.temperatureProperty
if (tempProp !== null) {
value = this.indiManager.getNumberPropertyValue(tempProp.device, tempProp.vector, tempProp.property);
} else {
value = { value: null, warning: null }
}
if (imagingSetup.dynState.curFocus!.temp !== value.value
|| imagingSetup.dynState.temperatureWarning !== value.warning) {
logger.info("Updated focuser temp to ", {imagingSetupUid, value});
imagingSetup.dynState.curFocus!.temp = value.value;
imagingSetup.dynState.temperatureWarning = value.warning;
}
}
refreshFocuserFilter(imagingSetupUid: string)
{
const instance = this.context.imagingSetupManager.getImagingSetupInstance(imagingSetupUid);
if (!instance.exists()) {
return;
}
const imagingSetup = instance.config();
if (imagingSetup.dynState.curFocus === null) {
imagingSetup.dynState.filterWheelWarning = null;
return;
}
let value;
let strValue;
const filterWheelDevice = imagingSetup.filterWheelDevice;
if (filterWheelDevice !== null) {
value = this.indiManager.getNumberPropertyValue(filterWheelDevice, 'FILTER_SLOT', 'FILTER_SLOT_VALUE');
if (value.value !== null) {
strValue = {
warning: value.warning,
value: this.context.filterWheel.getFilterId(filterWheelDevice, value.value),
}
} else {
strValue = {
value: null,
warning: value.warning
};
}
} else {
strValue = { value: null, warning: null };
}
if (imagingSetup.dynState.curFocus.filter !== strValue.value
|| imagingSetup.dynState.temperatureWarning !== strValue.warning) {
logger.info("Updated focuser filter to ", {imagingSetupUid, strValue});
imagingSetup.dynState.curFocus.filter = strValue.value;
imagingSetup.dynState.temperatureWarning = strValue.warning;
}
}
updateReferencePoint(imagingSetupUuid: string) {
this.refreshFocuserFilter(imagingSetupUuid);
this.refreshFocuserTemperature(imagingSetupUuid);
this.refreshFocuserPosition(imagingSetupUuid);
const config = this.context.imagingSetupManager.getImagingSetupInstance(imagingSetupUuid).config();
const dynState = config.dynState;
if (!dynState.curFocus) {
throw new Error("Focuser not ready");
}
const newRef = {...dynState.curFocus!, time: new Date().getTime()};
logger.info("Updating refernce point", newRef)
config.refFocus = newRef;
}
getAPI():RequestHandler.APIAppImplementor<BackOfficeAPI.FocuserAPI> {
return {
abort: this.abort,
focus: this.focus,
setCurrentImagingSetup: this.setCurrentImagingSetup,
sync: this.sync,
adjust: this.adjust,
}
}
resetCurrent(status: AutoFocusStatus['status'])
{
this.currentStatus.current = {
status: status,
imagingSetup: null,
error: null,
firstStep: null,
lastStep: null,
targetStep: null,
points: {},
predicted: {}
}
}
setCurrentStatus(status: AutoFocusStatus['status'], error: any)
{
this.currentStatus.current.status = status;
if (error) {
this.currentStatus.current.error = '' + (error.message || error);
}
}
private rawMoveFocuser = async(ct: CancellationToken, focuserId: string, position: number)=>{
await this.indiManager.setParam(ct, focuserId, 'ABS_FOCUS_POSITION', {
FOCUS_ABSOLUTE_POSITION: '' + position
},
false,
true,
(connection, devId, vectorId) => {
const vec = connection.getDevice(devId).getVector('FOCUS_ABORT_MOTION');
vec.setValues([{name: 'ABORT', value: 'On'}]);
}
);
}
// FIXME : Must receive an imagingSetupUuid and never refer to the current (which is only UI)
private getCurrentConfiguration(): {imagingSetupInstance: ImagingSetupInstance, camera: string, focuser: string, settings: FocuserSettings} {
const imagingSetupInstance = this.context.imagingSetupManager.getImagingSetupInstance(this.currentStatus.currentImagingSetup);
if (!imagingSetupInstance.exists()) {
throw new Error("No imaging setup selected");
}
const camera = imagingSetupInstance.config().cameraDevice;
if (camera === null) {
throw new Error("No camera selected");
}
if (!hasKey(this.camera.currentStatus.dynStateByDevices, camera)) {
throw new Error("Invalid camera");
}
const focuser = imagingSetupInstance.config().focuserDevice;
if (focuser === undefined || focuser === null) {
throw new Error("No focuser selected");
}
const settings = imagingSetupInstance.config().focuserSettings;
return {
imagingSetupInstance: imagingSetupInstance, camera, focuser, settings
}
}
// Adjust the focus
private async doFocus(ct: CancellationToken):Promise<number> {
const config = this.getCurrentConfiguration();
const imagingSetup:string = config.imagingSetupInstance.uid!;
this.currentStatus.current.imagingSetup = imagingSetup;
const amplitude = config.settings.range;
const stepCount = config.settings.steps;
const data:Array<number[]> = [];
logger.info("Starting focus", {camera: config.camera, focuser: config.focuser, settings: config.settings});
// Find focuser & camera.
const connection = this.indiManager.getValidConnection();
const focuserId = config.focuser;
// check device connected
const focuser = connection.getDevice(focuserId);
if (!focuser.isConnected()) {
logger.warn("Focuser not connected");
throw new Error("Focuser not connected");
}
if (!connection.getDevice(config.camera).isConnected()) {
logger.warn("Camera not connected");
throw new Error("Camera not connected");
}
// Move to the starting point
const absPos = focuser.getVector('ABS_FOCUS_POSITION');
if (!absPos.isReadyForOrder()) {
logger.warn("Focuser not ready");
throw new Error("Focuser is not ready");
}
let initialPos:number = parseFloat(absPos.getPropertyValue("FOCUS_ABSOLUTE_POSITION"));
let lastKnownPos:number = initialPos;
const start = config.settings.targetCurrentPos
? lastKnownPos
: config.settings.targetPos;
logger.info('start pos', {start});
let firstStep = Math.round(start - amplitude);
let lastStep = Math.round(start + amplitude);
let stepSize = Math.ceil(2 * amplitude / stepCount);
if (stepSize < 1) {
stepSize = 1;
}
if (firstStep < 0) {
firstStep = 0;
}
if (Math.abs(lastStep - firstStep) / stepSize < 5) {
logger.warn("Not enough step");
throw new Error("Not enough step - at least 5 required");
}
// FIXME: check lastStep < focuser max
const moveForward = config.settings.lowestFirst;
// Negative focus swap steps
if (!moveForward) {
const tmp = lastStep;
lastStep = firstStep;
firstStep = tmp;
}
this.currentStatus.current.firstStep = firstStep;
this.currentStatus.current.lastStep = lastStep;
let currentStep = firstStep;
let stepId = 0;
function nextStep() {
return currentStep + (moveForward ? stepSize : -stepSize);
}
function done(step:number) {
return moveForward ? step > lastStep : step < lastStep
}
// Move to currentStep
await this.moveFocuserWithBacklash(ct, imagingSetup,currentStep);
while(!done(currentStep)) {
logger.info('shoot start');
const shootResult = await this.camera.doShoot(ct, imagingSetup,
(settings)=>({
...settings,
prefix: 'focus_ISO8601_step_' + Math.floor(currentStep)
}));
const moveFocuserPromise = done(nextStep()) ? undefined : this.moveFocuserWithBacklash(ct, imagingSetup, nextStep());
try {
const starFieldResponse = await this.imageProcessor.compute(ct, {
starField: { source: {
path: shootResult.path,
streamId: "",
}}
});
const starField = starFieldResponse.stars;
logger.info('got starfield', {starCount: starField.length});
let fwhm:number|null = Algebra.starFieldFwhm(starField);
logger.info('fwhm result', {currentStep, fwhm});
if (isNaN(fwhm!)) {
fwhm = null;
}
if (fwhm !== null) {
data.push( [currentStep, fwhm ]);
}
this.currentStatus.current.points[currentStep] = {
fwhm: fwhm
};
currentStep = nextStep();
logger.debug('next step', {currentStep});
stepId++;
} finally {
await moveFocuserPromise;
}
}
if (data.length < 5) {
logger.warn('Could not find best position. Moving back to origin', {initialPos});
await this.moveFocuserWithBacklash(ct, imagingSetup, initialPos);
throw new Error("Not enough data for focus");
}
logger.info('regression', {data});
const result = new PolynomialRegression(data.map(e=>e[0]), data.map(e=>e[1]), 4);
// This is ugly. but works
const precision = Math.min(Math.abs(lastStep - firstStep), 128);
let bestValue = undefined;
let bestPos: number|undefined;
for(let i = 0; i <= precision; ++i) {
const pos = firstStep + (i === 0 ? 0 : i * (lastStep - firstStep) / precision);
const pred = result.predict(pos);
logger.debug('predict at : ' + i + '#' +pos+' => ' + JSON.stringify(pred));
const valueAtPos = pred;
this.currentStatus.current.predicted[pos] = {
fwhm: valueAtPos
};
if (i === 0 || bestValue > valueAtPos) {
bestValue = valueAtPos;
bestPos = pos;
}
}
logger.info('Found best position', {bestPos, bestValue});
await this.moveFocuserWithBacklash(ct, imagingSetup, bestPos!);
this.updateReferencePoint(imagingSetup);
return bestPos!;
}
setCurrentImagingSetup=async(ct:CancellationToken, message: {imagingSetup: string|null})=> {
if (message.imagingSetup !== null && !this.context.imagingSetupManager.getImagingSetupInstance(message.imagingSetup).exists()) {
throw new Error("invalid imaging setup");
}
this.currentStatus.currentImagingSetup = message.imagingSetup;
}
focus=async(ct:CancellationToken, message:{}):Promise<number>=>{
return await createTask<number>(ct, async (task)=>{
if (this.currentPromise !== null) {
throw new Error("Focus already started");
}
this.currentPromise = task;
try {
this.resetCurrent('running');
const ret:number = await this.doFocus(task.cancellation);
this.setCurrentStatus('done', null);
return ret;
} catch(e) {
if (e instanceof CancellationToken.CancellationError) {
this.setCurrentStatus('interrupted', e);
} else {
this.setCurrentStatus('error', e);
}
throw e;
} finally {
this.currentPromise = null;
}
});
}
abort=async(ct:CancellationToken, message: {})=>{
if (this.currentPromise !== null) {
this.currentPromise.cancel();
}
}
sync=async(ct:CancellationToken, payload: {imagingSetupUuid: string}) => {
await this.updateReferencePoint(payload.imagingSetupUuid);
}
getFocuserDelta=(imagingSetupUuid: string)=> {
const imagingSetup = this.context.imagingSetupManager.getImagingSetupInstance(imagingSetupUuid);
const imagingSetupConf = imagingSetup.config();
const imagingSetupDynState = imagingSetupConf.dynState;
const focusStepPerDegree = imagingSetupConf.focuserSettings?.focusStepPerDegree;
const focuserFilterAdjustment = imagingSetupConf.focuserSettings?.focuserFilterAdjustment;
const focusStepTolerance = imagingSetupConf.focuserSettings?.focusStepTolerance;
const temperatureProperty = imagingSetupConf.focuserSettings?.temperatureProperty;
return FocuserDelta.getFocusDelta({
curFocus: imagingSetupDynState.curFocus,
refFocus: imagingSetupConf.refFocus,
focusStepPerDegree,
focusStepTolerance,
focuserFilterAdjustment,
temperatureProperty
});
}
private getGuidingInhibiter=(imagingSetupUuid: string): PhdGuideInhibiter => {
if (this.needGuideInhibition(imagingSetupUuid)) {
return this.context.phd.createInhibiter();
} else {
return {
start:async ()=>{},
end:async ()=>{},
}
}
}
public needGuideInhibition=(imagingSetupUuid: string) => {
const imagingSetup = this.context.imagingSetupManager.getImagingSetupInstance(imagingSetupUuid);
const imagingSetupConf = imagingSetup.config();
return imagingSetupConf.focuserSettings.interruptGuiding;
}
adjust=async(ct:CancellationToken, payload: {imagingSetupUuid: string}) => {
const targetPos = this.getFocuserDelta(payload.imagingSetupUuid);
if (targetPos.fromCur !== 0) {
const guidingInhibiter = this.getGuidingInhibiter(payload.imagingSetupUuid);
try {
await guidingInhibiter.start(ct);
await this.moveFocuserWithBacklash(ct, payload.imagingSetupUuid, targetPos.abs);
} finally {
await guidingInhibiter.end(ct);
}
}
}
}