-
Notifications
You must be signed in to change notification settings - Fork 2
/
Astrometry.ts
523 lines (460 loc) · 20.7 KB
/
Astrometry.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
import CancellationToken from 'cancellationtoken';
import Log from './Log';
import * as BackOfficeAPI from './shared/BackOfficeAPI';
import * as RequestHandler from './RequestHandler';
import ConfigStore from './ConfigStore';
import { ExpressApplication, AppContext } from "./ModuleBase";
import { AstrometryStatus, BackofficeStatus, AstrometryWizard, AstrometrySettings } from './shared/BackOfficeStatus';
import { AstrometryResult, ProcessorAstrometryRequest } from './shared/ProcessorTypes';
import JsonProxy from './shared/JsonProxy';
import { IndiConnection } from './Indi';
import SkyProjection from './SkyAlgorithms/SkyProjection';
import {Task, createTask} from "./Task";
import Wizard from "./Wizard";
import PolarAlignmentWizard from "./PolarAlignmentWizard";
const logger = Log.logger(__filename);
const defaultSettings = ():AstrometrySettings=> ({
initialFieldMin: 0.2,
initialFieldMax: 5,
useMountPosition: true,
initialSearchRadius: 30,
narrowedSearchRadius: 4,
narrowedFieldPercent: 25,
polarAlign: {
slewRate: "SLEW_FIND",
sampleCount: 5,
angle: 60,
minAltitude: 10,
},
preferedScope: null,
preferedImagingSetup: null,
});
// Astrometry requires: a camera, a mount
export default class Astrometry implements RequestHandler.APIAppProvider<BackOfficeAPI.AstrometryAPI>{
appStateManager: JsonProxy<BackofficeStatus>;
readonly context: AppContext;
currentStatus: AstrometryStatus;
currentProcess: Task<any>|null = null;
get imageProcessor() { return this.context.imageProcessor };
get indiManager() { return this.context.indiManager };
get camera() { return this.context.camera };
runningWizard: null|Wizard = null;
constructor(app:ExpressApplication, appStateManager:JsonProxy<BackofficeStatus>, context: AppContext) {
this.appStateManager = appStateManager;
const initialStatus: AstrometryStatus = {
status: "empty",
lastOperationError: null,
scopeStatus: "idle",
scopeReady: true,
scopeMovedSinceImage: false,
scopeDetails: "not initialised",
image: null,
result: null,
selectedScope: null,
target: null,
settings: defaultSettings(),
narrowedField: null,
useNarrowedSearchRadius: false,
runningWizard: null,
currentImagingSetup: null,
};
this.appStateManager.getTarget().astrometry = initialStatus;
this.currentStatus = this.appStateManager.getTarget().astrometry;
this.context = context;
new ConfigStore<AstrometrySettings>(appStateManager, 'astrometry', ['astrometry', 'settings'],
defaultSettings(),
defaultSettings(),
(c)=>{
// Adjust here if required
return c;
}
);
// listener to adjust scopeStatus (only when ok/ko)
this.appStateManager.addSynchronizer([
[
[ 'indiManager', 'deviceTree', null, 'CONNECTION', 'childs', 'CONNECT' ],
[ 'astrometry', 'selectedScope' ]
]
],
this.syncScopeStatus, true
);
context.indiManager.createPreferredDeviceSelector<AstrometryStatus>({
availablePreferedCurrentPath: [
[
[ 'indiManager' , 'availableScopes'],
[ 'astrometry' , 'settings', 'preferedScope'],
[ 'astrometry' , 'selectedScope'],
]
],
read: ()=> ({
available: this.indiManager.currentStatus.availableScopes,
prefered: this.currentStatus.settings.preferedScope,
current: this.currentStatus.selectedScope,
}),
set: (s:{prefered?: string|null|undefined, current?: string|null|undefined})=>{
if (s.prefered !== undefined) {
this.currentStatus.settings.preferedScope = s.prefered;
}
if (s.current !== undefined) {
this.currentStatus.selectedScope = s.current;
}
}
});
context.imagingSetupManager.createPreferredImagingSelector({
currentPath: [ 'astrometry', 'currentImagingSetup' ],
preferedPath: [ 'astrometry', 'settings', 'preferedImagingSetup' ],
read: ()=> ({
prefered: this.currentStatus.settings.preferedImagingSetup,
current: this.currentStatus.currentImagingSetup,
}),
set: (s:{prefered?: string|null|undefined, current?: string|null|undefined})=>{
if (s.prefered !== undefined) {
this.currentStatus.settings.preferedImagingSetup = s.prefered;
}
if (s.current !== undefined) {
this.currentStatus.currentImagingSetup = s.current;
}
}
});
}
private readonly syncScopeStatus=()=>
{
try {
if (this.currentStatus.selectedScope === null) {
throw new Error("no scope selected");
}
const connection = this.context.indiManager.getValidConnection();
const device = connection.getDevice(this.currentStatus.selectedScope);
if (device.getVector('CONNECTION').getPropertyValueIfExists('CONNECT') !== 'On') {
throw new Error("scope not connected");
}
this.currentStatus.scopeReady = true;
this.currentStatus.scopeDetails = null;
} catch(e) {
this.currentStatus.scopeReady = false;
this.currentStatus.scopeDetails = e.message || (""+e);
}
}
getAPI(): RequestHandler.APIAppImplementor<BackOfficeAPI.AstrometryAPI> {
return {
updateCurrentSettings: this.updateCurrentSettings,
setCurrentImagingSetup: this.setCurrentImagingSetup,
compute: this.wizardProtectedApi(this.compute),
cancel: this.wizardProtectedApi(this.cancel),
setScope: this.setScope,
goto: this.wizardProtectedApi(this.goto),
sync: this.wizardProtectedApi(this.sync),
startPolarAlignmentWizard: this.startPolarAlignmentWizard,
wizardNext: this.wizardNext,
wizardInterrupt: this.wizardInterrupt,
wizardQuit: this.wizardQuit,
}
}
setCurrentImagingSetup=async (ct: CancellationToken, message:{imagingSetup:null|string})=>{
if (message.imagingSetup !== null && !this.context.imagingSetupManager.getImagingSetupInstance(message.imagingSetup).exists()) {
throw new Error("invalid imaging setup");
}
this.currentStatus.currentImagingSetup = message.imagingSetup;
}
updateCurrentSettings = async (ct: CancellationToken, payload: {diff: any}) => {
const newSettings = JsonProxy.applyDiff(this.currentStatus.settings, payload.diff);
// FIXME: do the checking !
this.currentStatus.settings = newSettings;
}
wizardProtectedApi = <A, B>(process: (ct: CancellationToken, message:A)=>Promise<B>)=>{
return async (ct: CancellationToken, message: A) => {
if (this.currentStatus.runningWizard !== null
&& !this.currentStatus.runningWizard.paused) {
throw new Error(this.currentStatus.runningWizard.id + " in progress - can't continue");
}
return await process(ct, message);
}
}
compute = async(ct: CancellationToken, message:BackOfficeAPI.AstrometryComputeRequest)=>{
return await createTask<AstrometryResult>(ct, async (task) => {
if (this.currentProcess !== null) {
throw new Error("Astrometry already in process");
}
const finish = (status: AstrometryStatus['status'], error:string|null, result:AstrometryResult|null)=> {
this.currentProcess = null;
this.currentStatus.status = status;
this.currentStatus.lastOperationError = error;
this.currentStatus.result = result;
if (this.currentStatus.result !== null && this.currentStatus.result.found) {
const skyProjection = SkyProjection.fromAstrometry(this.currentStatus.result);
// Compute the narrowed field
this.currentStatus.narrowedField = skyProjection.getFieldSize(this.currentStatus.result.width, this.currentStatus.result.height);
}
};
let result: AstrometryResult;
this.currentProcess = task;
try {
this.currentStatus.image = message.image;
this.currentStatus.scopeMovedSinceImage = false;
this.currentStatus.status = 'computing';
this.currentStatus.result = null;
this.currentStatus.target = null;
this.currentStatus.lastOperationError = null;
const astrometry:ProcessorAstrometryRequest = {
"exePath": "",
"libraryPath": "",
"fieldMin":
this.currentStatus.narrowedField !== null && !message.forceWide
? this.currentStatus.narrowedField * 100 / (100 + this.currentStatus.settings.narrowedFieldPercent)
: this.currentStatus.settings.initialFieldMin,
"fieldMax":
this.currentStatus.narrowedField !== null && !message.forceWide
? this.currentStatus.narrowedField * (100 + this.currentStatus.settings.narrowedFieldPercent) / 100
: this.currentStatus.settings.initialFieldMax,
"raCenterEstimate": 0,
"decCenterEstimate": 0,
"searchRadius": 180,
"numberOfBinInUniformize": 10,
"source": {
"source": {
"path": message.image,
streamId: "",
}
}
}
if (this.currentStatus.settings.useMountPosition) {
// Use scope position, with either small or large radius
try {
const targetScope = this.currentStatus.selectedScope;
if (!targetScope) {
throw new Error('No mount selected');
}
this.context.indiManager.checkDeviceConnected(targetScope);
const mountDevice = this.context.indiManager.getValidConnection().getDevice(targetScope);
const vector = mountDevice.getVector('EQUATORIAL_EOD_COORD');
if (!vector.isReadyForOrder()) {
throw new Error("Mount is busy");
}
const scopeRa = parseFloat(vector.getPropertyValue("RA"));
const scopeDec = parseFloat(vector.getPropertyValue("DEC"));
if (isNaN(scopeRa)||isNaN(scopeDec)) {
throw new Error("Invalid mount position");
}
const j2000Center = SkyProjection.J2000RaDecFromEpoch([scopeRa*360/24, scopeDec], Date.now());
astrometry.raCenterEstimate = j2000Center[0];
astrometry.decCenterEstimate = j2000Center[1];
const radius = this.currentStatus.useNarrowedSearchRadius && !message.forceWide
? this.currentStatus.settings.narrowedSearchRadius
: this.currentStatus.settings.initialSearchRadius;
astrometry.searchRadius = radius !== null ? radius : 180;
} catch(e) {
logger.warn('Astrometry problem with mount - doing wide scan', e);
}
}
logger.info('Starting astrometry', {astrometry});
result = await this.imageProcessor.compute(task.cancellation, {astrometry});
} catch(e) {
if (e instanceof CancellationToken.CancellationError) {
finish('empty', null, null);
} else {
finish('error', e.message || '' + e, null);
}
throw e;
}
finish('ready', null, result);
return result;
});
}
cancel = async (ct: CancellationToken, message: {})=>{
if (this.currentProcess !== null) {
this.currentProcess.cancel("user cancel");
}
}
setScope = async (ct: CancellationToken, message: {deviceId: string})=>{
if (this.indiManager.currentStatus.availableScopes.indexOf(message.deviceId) === -1) {
throw new Error("device not available");
}
this.currentStatus.selectedScope = message.deviceId;
}
goto = async (ct: CancellationToken, message:BackOfficeAPI.AstrometryGotoScopeRequest)=>{
return await createTask<void>(ct, async (task) => {
if (this.currentProcess !== null) {
throw new Error("Astrometry already in process");
}
const targetScope = this.currentStatus.selectedScope;
if (!targetScope) {
throw new Error("No scope selected for astrometry");
}
const finish = (status: AstrometryStatus['scopeStatus'], error:string|null)=> {
this.currentProcess = null;
this.currentStatus.scopeStatus = status;
this.currentStatus.lastOperationError = error;
};
logger.info('Astrometry: goto', message);
this.currentProcess = task;
try {
this.currentStatus.scopeStatus = 'moving';
this.currentStatus.scopeMovedSinceImage = true;
this.currentStatus.lastOperationError = null;
this.currentStatus.target = {ra:message.ra, dec:message.dec};
// check no motion is in progress
await this.context.indiManager.setParam(
task.cancellation,
targetScope,
'ON_COORD_SET',
{'TRACK': 'On'},
true,
true);
await this.context.indiManager.setParam(
task.cancellation,
targetScope,
'EQUATORIAL_EOD_COORD',
{
'RA': ''+ message.ra * 24 / 360,
'DEC': '' + message.dec,
},
true,
true,
// Aborter...
(connection:IndiConnection, devId:string)=>{
logger.info('Cancel requested');
const dev = connection.getDevice(devId);
const vec = dev.getVector("TELESCOPE_ABORT_MOTION")
vec.setValues([{name:"ABORT", value:"On"}]);
});
} catch(e) {
if (e instanceof CancellationToken) {
finish('idle', null);
} else {
finish('idle', e.message || ('' + e));
}
throw e;
}
finish('idle', null);
});
}
sync = async (ct: CancellationToken, message: {})=>{
return await createTask<void>(ct, async (task) => {
if (this.currentProcess !== null) {
throw new Error("Astrometry already in process");
}
if (this.currentStatus.result === null) {
throw new Error("Run astrometry first");
}
if (!this.currentStatus.result.found) {
throw new Error("Astrometry failed, cannot sync");
}
const targetScope = this.currentStatus.selectedScope;
if (!targetScope) {
throw new Error("No scope selected for astrometry");
}
logger.info('Astrometry: sync');
const finish = (status: AstrometryStatus['scopeStatus'], error:string|null)=> {
this.currentProcess = null;
this.currentStatus.scopeStatus = status;
this.currentStatus.lastOperationError = error;
};
this.currentProcess = task;
try {
this.currentStatus.scopeStatus = 'syncing';
this.currentStatus.lastOperationError = null;
this.currentStatus.target = null;
const skyProjection = SkyProjection.fromAstrometry(this.currentStatus.result);
// take the center of the image
const center = [(this.currentStatus.result.width - 1) / 2, (this.currentStatus.result.height - 1) / 2];
// Project to J2000
const [ra2000, dec2000] = skyProjection.pixToRaDec(center);
// compute JNOW center for last image.
const [ranow, decnow] = SkyProjection.raDecEpochFromJ2000([ra2000, dec2000], Date.now());
// Check that scope is connected
this.context.indiManager.checkDeviceConnected(targetScope);
// true,true=> check no motion is in progress
logger.info('Setting ON_COORD_SET', {targetScope});
await this.context.indiManager.setParam(
task.cancellation,
targetScope,
'ON_COORD_SET',
{'SYNC': 'On'},
true,
true);
logger.info('Setting EQUATORIAL_EOD_COORD', {targetScope, ranow, decnow});
await this.context.indiManager.setParam(
task.cancellation,
targetScope,
'EQUATORIAL_EOD_COORD',
{
'RA': ''+ ranow * 24 / 360,
'DEC': '' + decnow,
},
true,
true);
} catch(e) {
if (e instanceof CancellationToken.CancellationError) {
finish('idle', null)
} else {
finish('idle', e.message || ('' + e));
}
throw e;
}
this.currentStatus.useNarrowedSearchRadius = true;
finish('idle', null);
});
}
setWizard = (id: string, wizardBuilder:()=>Wizard) => {
if (this.currentProcess !== null) {
throw new Error("Astrometry is Busy");
}
if (this.currentStatus.runningWizard !== null) {
if (!this.currentStatus.runningWizard.paused) {
throw new Error(this.currentStatus.runningWizard.id + " already in progress");
}
this.runningWizard!.discard();
this.runningWizard = null;
}
this.currentStatus.runningWizard = {
id,
title: id,
paused: false,
interruptible: false,
hasNext: null,
};
try {
this.runningWizard = wizardBuilder();
} catch(e) {
this.currentStatus.runningWizard = null;
throw e;
}
this.runningWizard.start();
}
wizardQuit = async (ct:CancellationToken, message: {})=> {
if (!this.currentStatus.runningWizard) {
return;
}
if (!this.currentStatus.runningWizard.paused) {
throw new Error("Cannot quit: not paused");
}
try {
this.runningWizard!.discard();
} catch(e) {
logger.warn("unable to discard", e);
}
this.runningWizard = null;
this.currentStatus.runningWizard = null;
}
wizardInterrupt = async(ct:CancellationToken, message:{})=> {
if (!this.currentStatus.runningWizard) {
return;
}
if (this.currentStatus.runningWizard.paused) {
return;
}
this.runningWizard!.interrupt();
}
wizardNext = async(ct:CancellationToken, message:{})=> {
if (!this.currentStatus.runningWizard) {
return;
}
if (!this.currentStatus.runningWizard.hasNext) {
return;
}
this.runningWizard!.next();
}
startPolarAlignmentWizard = async (ct: CancellationToken, message: {}) => {
this.setWizard("polarAlignment", ()=>new PolarAlignmentWizard(this));
}
}