-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplanewave_mountd
executable file
·651 lines (523 loc) · 26.4 KB
/
planewave_mountd
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
#!/usr/bin/env python3
#
# This file is part of the Robotic Observatory Control Kit (rockit)
#
# rockit is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# rockit is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with rockit. If not, see <http://www.gnu.org/licenses/>.
"""Daemon for controlling a Planewave L mount through its http interface via Pyro"""
import argparse
import threading
import time
from astropy.coordinates import AltAz, FK5, ICRS, SkyCoord, EarthLocation, get_moon, get_sun
from astropy.time import Time
import astropy.units as u
import requests
import Pyro4
from rockit.common import log, TryLock
from rockit.common.helpers import pyro_client_matches
from rockit.mount.planewave import CommandStatus, Config, MountState
def _parse_mountstate(status, is_homing=False):
"""Parse a MountState value from the PWI status dictionary"""
if status is None or status['mount.is_connected'] != 'true':
return MountState.Disabled
# Work around is_slewing being false while homing
if is_homing:
ha_moving = status['mount.axis0.setpoint_velocity_degs_per_sec'] != '0'
dec_moving = status['mount.axis1.setpoint_velocity_degs_per_sec'] != '0'
if ha_moving or dec_moving:
return MountState.Homing
if status['mount.axis0.is_homed'] != 'true' or status['mount.axis1.is_homed'] != 'true':
return MountState.NotHomed
# Simplify the external API we expose by treating unpowered axes as parked
if status['mount.axis0.is_enabled'] != 'true' or status['mount.axis1.is_enabled'] != 'true':
return MountState.Parked
if status['mount.is_slewing'] == 'true':
return MountState.Slewing
if status['mount.is_tracking'] == 'true':
return MountState.Tracking
return MountState.Stopped
def _parse_location(status):
"""Parse an astropy EarthLocation value from the PWI status dictionary"""
return EarthLocation(
lat=status['site.latitude_degs'],
lon=status['site.longitude_degs'],
height=status['site.height_meters'])
class MountDaemon:
"""Daemon interface for talon subsystems"""
def __init__(self, config):
self._config = config
self._is_homing = False
self._ha_positive_limit = self._config.ha_soft_limits[1] * u.deg
self._ha_negative_limit = self._config.ha_soft_limits[0] * u.deg
self._dec_positive_limit = self._config.dec_soft_limits[1] * u.deg
self._dec_negative_limit = self._config.dec_soft_limits[0] * u.deg
self._pointing_condition = threading.Condition()
self._force_stopped = False
# Only one command may be active at a time (except for stop)
self._command_lock = threading.Lock()
def _request_with_status(self, command, **kwargs):
"""
Send a command to PWI4 and return its status response
Returns None if the command failed or a dictionary of the mount status
"""
try:
url = f'http://{self._config.pwi_host}:{self._config.pwi_port}/{command}'
response = requests.get(url, timeout=self._config.pwi_timeout, params=kwargs)
response.raise_for_status()
data = response.text.split("\n")
status = {}
for line in data:
fields = line.split("=", 1)
if len(fields) == 2:
status[fields[0]] = fields[1]
return status
except Exception:
return None
def _validate_pointing(self, coords, log_failed_prefix):
"""
Check whether the given coordinate is within our soft HA and Dec limits.
Returns CommandStatus.Succeeded if valid, otherwise logs and returns the appropriate error status
"""
icrs = coords.icrs
lst = Time(coords.obstime, location=coords.location).sidereal_time('apparent')
ha = (lst - icrs.ra).wrap_at(12 * u.hourangle)
dec = icrs.dec
if ha < self._ha_negative_limit or ha > self._ha_positive_limit:
log.error(self._config.log_name, log_failed_prefix + f'; ha {ha} outside limit ' +
f'({self._ha_negative_limit}, {self._ha_positive_limit})')
return CommandStatus.OutsideHALimits
if dec < self._dec_negative_limit or dec > self._dec_positive_limit:
log.error(self._config.log_name, log_failed_prefix + f'; dec {dec} outside limit ' +
f'({self._dec_negative_limit}, {self._dec_positive_limit})')
return CommandStatus.OutsideDecLimits
return CommandStatus.Succeeded
def _set_axis_power(self, enabled):
"""
Send a mount/(enable|disable) command.
Returns True on success or logs and returns False on error
"""
command = 'enable' if enabled else 'disable'
if self._request_with_status('mount/' + command, axis=-1) is None:
log.error(self._config.log_name, 'Failed to ' + command + ' motor power')
return False
# Wait momentarily for the state to change
time.sleep(1)
return True
def _point(self, command, expected_state, is_homing=False, **kwargs):
"""
Send a mount/goto_* command and wait for slewing to complete.
Returns True on success or logs and returns False on error
"""
if is_homing:
poll_interval = self._config.home_poll_interval
timeout = self._config.home_timeout
slewing_state = MountState.Homing
else:
poll_interval = self._config.slew_poll_interval
timeout = self._config.slew_timeout
slewing_state = MountState.Slewing
with self._pointing_condition:
if self._request_with_status(command, **kwargs) is None:
log.error(self._config.log_name, 'Pointing failed: failed to issue ' + command)
start = Time.now()
while True:
# Note: it can take a few milliseconds before the slew begins
# Wait an interval period so we don't exit too early
self._pointing_condition.wait(poll_interval)
if self._force_stopped:
break
status = self._request_with_status('status')
state = _parse_mountstate(status, is_homing)
if state != slewing_state or (Time.now() - start).to_value(u.s) > timeout:
break
if self._force_stopped:
log.error(self._config.log_name, 'Pointing failed: aborted')
return False
if state == expected_state:
return True
self._request_with_status('mount/stop')
if state == MountState.Slewing:
log.error(self._config.log_name, 'Pointing failed: timed out')
else:
log.error(self._config.log_name, f'Pointing failed: completed with {MountState.label(state)} instead of ' +
MountState.label(expected_state))
return False
@Pyro4.expose
def report_status(self):
"""Returns a dictionary containing the current telescope state"""
status = self._request_with_status('status')
if status is None:
return {
'date': Time.now().strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
'state': MountState.Disabled,
'state_label': MountState.label(MountState.Disabled),
}
state = _parse_mountstate(status, self._is_homing)
location = _parse_location(status)
# Prefer the mount timestamp if we have it - this was when the coordinates were calculated
# If the mount is not connected we can safely fall back to the request timestamp
if state == MountState.Disabled:
timestamp = status['response.timestamp_utc']
else:
timestamp = status['mount.timestamp_utc']
date = Time(Time.strptime(timestamp, '%Y-%m-%d %H:%M:%S.%f'), location=location)
data = {
'date': date.strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
'state': state,
'state_label': MountState.label(state),
'pwi_version': status['pwi4.version'],
'site_latitude': location.lat.to_value(u.deg),
'site_longitude': location.lon.to_value(u.deg),
'site_elevation': location.height.to_value(u.m),
}
if state != MountState.Disabled:
lst = u.Quantity(status['site.lmst_hours'], unit=u.hourangle)
data.update({
'lst': lst.to_value(u.deg),
})
if state >= MountState.Parked:
pointing = SkyCoord(
ra=status['mount.ra_j2000_hours'],
dec=status['mount.dec_j2000_degs'],
unit=(u.hourangle, u.deg),
frame='icrs')
data.update({
'ra': pointing.ra.to_value(u.deg),
'dec': pointing.dec.to_value(u.deg),
'offset_ra': 0,
'offset_dec': 0,
# Note: this field depends on a custom patched version of pwi4
'ha': u.Quantity(status['mount.ha_hours'], unit=u.hourangle).to_value(u.deg),
'alt': u.Quantity(status['mount.altitude_degs'], unit=u.deg).to_value(u.deg),
'az': u.Quantity(status['mount.azimuth_degs'], unit=u.deg).to_value(u.deg),
'moon_separation': get_moon(date).separation(pointing).to_value(u.deg),
'sun_separation': get_sun(date).separation(pointing).to_value(u.deg),
})
return data
@Pyro4.expose
def find_homes(self):
"""Finds the mount home positions"""
if not pyro_client_matches(self._config.control_ips):
return CommandStatus.InvalidControlIP
with TryLock(self._command_lock) as success:
if not success:
return CommandStatus.Blocked
status = self._request_with_status('status')
state = _parse_mountstate(status)
if state == MountState.Disabled:
return CommandStatus.MountNotInitialized
# Enable axes if needed
axes_powered = status['mount.axis0.is_enabled'] == 'true' and status['mount.axis1.is_enabled'] == 'true'
if not axes_powered and not self._set_axis_power(True):
return CommandStatus.Failed
log.info(self._config.log_name, 'Homing axes')
try:
self._is_homing = True
if not self._point('mount/find_home', MountState.Stopped, is_homing=True):
log.error(self._config.log_name, 'Failed to issue home command')
return CommandStatus.Failed
finally:
self._is_homing = False
# Restore previous power state
if not axes_powered and not self._set_axis_power(False):
return CommandStatus.Failed
log.info(self._config.log_name, 'Homing complete')
return CommandStatus.Succeeded
@Pyro4.expose
def initialize(self):
"""Connect to mount and enable motor power"""
if not pyro_client_matches(self._config.control_ips):
return CommandStatus.InvalidControlIP
with TryLock(self._command_lock) as success:
if not success:
return CommandStatus.Blocked
status = self._request_with_status('status')
if status is None:
return CommandStatus.MountControlNotRunning
state = _parse_mountstate(status)
if state != MountState.Disabled:
return CommandStatus.MountNotDisabled
if self._request_with_status('mount/connect') is None:
log.error(self._config.log_name, 'Failed to connect to mount')
return CommandStatus.Failed
# Wait a second for the mount to respond before double checking that things are how we expect
time.sleep(1)
status = self._request_with_status('status')
state = _parse_mountstate(status)
return CommandStatus.Failed if state == MountState.Disabled else CommandStatus.Succeeded
@Pyro4.expose
def shutdown(self):
"""Disables motor power and disconnects from mount"""
if not pyro_client_matches(self._config.control_ips):
return CommandStatus.InvalidControlIP
with TryLock(self._command_lock) as success:
if not success:
return CommandStatus.Blocked
status = self._request_with_status('status')
state = _parse_mountstate(status)
if state == MountState.Disabled:
return CommandStatus.MountNotInitialized
if state != MountState.Parked and not self._set_axis_power(False):
return CommandStatus.Failed
if self._request_with_status('mount/disconnect') is None:
log.error(self._config.log_name, 'Failed to disconnect from mount')
return CommandStatus.Failed
return CommandStatus.Succeeded
@Pyro4.expose
def stop(self):
"""Stops any active telescope movement"""
if not pyro_client_matches(self._config.control_ips):
return CommandStatus.InvalidControlIP
with self._pointing_condition:
self._force_stopped = True
status = self._request_with_status('mount/stop')
state = _parse_mountstate(status)
if state == MountState.Disabled:
return CommandStatus.MountNotInitialized
self._pointing_condition.notify_all()
# Block until any other pointing commands have terminated before cleaning up
with self._command_lock:
self._force_stopped = False
return CommandStatus.Succeeded
@Pyro4.expose
def slew_altaz(self, alt_deg, az_deg):
"""Moves the telescope to a specified alt, az"""
if not pyro_client_matches(self._config.control_ips):
return CommandStatus.InvalidControlIP
with TryLock(self._command_lock) as success:
if not success:
return CommandStatus.Blocked
# Check against telescope limits
status = self._request_with_status('status')
state = _parse_mountstate(status)
if state == MountState.NotHomed:
return CommandStatus.MountNotHomed
if state == MountState.Parked and not self._set_axis_power(True):
return CommandStatus.Failed
location = _parse_location(status)
coords = SkyCoord(alt=alt_deg, az=az_deg, unit=u.deg, frame='altaz',
location=location, obstime=Time.now())
valid_status = self._validate_pointing(coords, f'failed to move to alt {alt_deg} az {az_deg}')
if valid_status != CommandStatus.Succeeded:
return valid_status
success = self._point('mount/goto_alt_az', MountState.Stopped, alt_degs=alt_deg, az_degs=az_deg)
return CommandStatus.Succeeded if success else CommandStatus.Failed
@Pyro4.expose
def park(self, position):
"""Moves the telescope to a named park position and disables axis power"""
if not pyro_client_matches(self._config.control_ips):
return CommandStatus.InvalidControlIP
with TryLock(self._command_lock) as success:
if not success:
return CommandStatus.Blocked
if position not in self._config.park_positions:
return CommandStatus.UnknownParkPosition
status = self._request_with_status('status')
state = _parse_mountstate(status)
if state == MountState.NotHomed:
return CommandStatus.MountNotHomed
if state == MountState.Parked and not self._set_axis_power(True):
return CommandStatus.Failed
park = self._config.park_positions[position]
if not self._point('mount/goto_alt_az', MountState.Stopped, alt_degs=park['alt'], az_degs=park['az']):
return CommandStatus.Failed
if not self._set_axis_power(False):
return CommandStatus.Failed
return CommandStatus.Succeeded
@Pyro4.expose
def slew_hadec(self, ha_deg, dec_deg):
"""Moves the telescope to a specified apparent ha, dec"""
if not pyro_client_matches(self._config.control_ips):
return CommandStatus.InvalidControlIP
with TryLock(self._command_lock) as success:
if not success:
return CommandStatus.Blocked
# Convert apparent HA, Dec to Alt, Az for pointing
now = Time.now()
status = self._request_with_status('status')
state = _parse_mountstate(status)
if state == MountState.NotHomed:
return CommandStatus.MountNotHomed
if state == MountState.Parked and not self._set_axis_power(True):
return CommandStatus.Failed
location = _parse_location(status)
coords = SkyCoord(
ra=Time(now, location=location).sidereal_time('apparent') - ha_deg * u.deg,
dec=dec_deg * u.deg,
frame=FK5(equinox=now),
obstime=now).transform_to(AltAz(obstime=now, location=location))
# Check against telescope limits
valid_status = self._validate_pointing(coords, f'failed to move to ha {ha_deg} dec {dec_deg}')
if valid_status != CommandStatus.Succeeded:
return valid_status
success = self._point('mount/goto_alt_az', MountState.Stopped,
alt_degs=coords.alt.to_value(u.deg),
az_degs=coords.az.to_value(u.deg))
return CommandStatus.Succeeded if success else CommandStatus.Failed
@Pyro4.expose
def slew_radec(self, ra_deg, dec_deg):
"""Moves the telescope to a specified J2000 ra, dec"""
if not pyro_client_matches(self._config.control_ips):
return CommandStatus.InvalidControlIP
with TryLock(self._command_lock) as success:
if not success:
return CommandStatus.Blocked
# Convert apparent RA, Dec to Alt, Az for pointing
now = Time.now()
status = self._request_with_status('status')
state = _parse_mountstate(status)
if state == MountState.NotHomed:
return CommandStatus.MountNotHomed
if state == MountState.Parked and not self._set_axis_power(True):
return CommandStatus.Failed
location = _parse_location(status)
coords = SkyCoord(
ra=ra_deg * u.deg,
dec=dec_deg * u.deg,
frame='icrs').transform_to(AltAz(obstime=now, location=location))
# Check against telescope limits
valid_status = self._validate_pointing(coords, f'failed to move to ra {ra_deg} dec {dec_deg}')
if valid_status != CommandStatus.Succeeded:
return valid_status
success = self._point('mount/goto_alt_az', MountState.Stopped,
alt_degs=coords.alt.to_value(u.deg),
az_degs=coords.az.to_value(u.deg))
return CommandStatus.Succeeded if success else CommandStatus.Failed
@Pyro4.expose
def track_radec(self, ra_deg, dec_deg):
"""Moves the telescope to a specified J2000 ra, dec and track at the sidereal rate"""
if not pyro_client_matches(self._config.control_ips):
return CommandStatus.InvalidControlIP
with TryLock(self._command_lock) as success:
if not success:
return CommandStatus.Blocked
status = self._request_with_status('status')
state = _parse_mountstate(status)
if state == MountState.NotHomed:
return CommandStatus.MountNotHomed
if state == MountState.Parked and not self._set_axis_power(True):
return CommandStatus.Failed
location = _parse_location(status)
coords = SkyCoord(
ra=ra_deg * u.deg,
dec=dec_deg * u.deg,
frame='icrs',
obstime=Time(Time.now(), location=location))
# Check against telescope limits
valid_status = self._validate_pointing(coords, f'failed to move to ra {ra_deg} dec {dec_deg}')
if valid_status != CommandStatus.Succeeded:
return valid_status
success = self._point('mount/goto_ra_dec_j2000', MountState.Tracking,
ra_hours=coords.ra.to_value(u.hourangle),
dec_degs=coords.dec.to_value(u.deg))
return CommandStatus.Succeeded if success else CommandStatus.Failed
@Pyro4.expose
def offset_radec(self, ra_delta_deg, dec_delta_deg):
"""Offsets the telescope relative to the current position"""
if not pyro_client_matches(self._config.control_ips):
return CommandStatus.InvalidControlIP
with TryLock(self._command_lock) as success:
if not success:
return CommandStatus.Blocked
status = self._request_with_status('status')
state = _parse_mountstate(status)
if state == MountState.NotHomed:
return CommandStatus.MountNotHomed
if state == MountState.Parked and not self._set_axis_power(True):
return CommandStatus.Failed
location = _parse_location(status)
now = Time(Time.now(), location=location)
if state == MountState.Tracking:
coords = SkyCoord(
ra=u.Quantity(status['mount.ra_j2000_hours'], unit=u.hourangle) + ra_delta_deg * u.deg,
dec=u.Quantity(status['mount.dec_j2000_degs'], unit=u.deg) + dec_delta_deg * u.deg,
frame='icrs',
obstime=now)
# Check against telescope limits
valid_status = self._validate_pointing(coords,
f'failed to offset by ra {ra_delta_deg} dec {dec_delta_deg}')
if valid_status != CommandStatus.Succeeded:
return valid_status
success = self._point('mount/offset', state,
ra_add_arcsec=3600 * ra_delta_deg,
dec_add_arcsec=3600 * dec_delta_deg)
else:
# The mount/offset command only works when the mount is tracking,
# so issue a mount/goto_alt_az command instead
coords = SkyCoord(
alt=status['mount.altitude_degs'],
az=status['mount.azimuth_degs'],
unit=u.deg,
frame='altaz',
obstime=now,
location=location).transform_to(ICRS)
coords = SkyCoord(
ra=coords.ra + ra_delta_deg * u.deg,
dec=coords.dec + dec_delta_deg * u.deg,
frame='icrs').transform_to(AltAz(obstime=now, location=location))
# Check against telescope limits
valid_status = self._validate_pointing(coords,
f'failed to offset by ra {ra_delta_deg} dec {dec_delta_deg}')
if valid_status != CommandStatus.Succeeded:
return valid_status
success = self._point('mount/goto_alt_az', MountState.Stopped,
alt_degs=coords.alt.to_value(u.deg),
az_degs=coords.az.to_value(u.deg))
return CommandStatus.Succeeded if success else CommandStatus.Failed
@Pyro4.expose
def track_tle(self, line1, line2, line3):
"""Tracks a TLE
WARNING: Telescope limits are not enforced: it is up to the caller to ensure we don't point at the floor!
"""
if not pyro_client_matches(self._config.control_ips):
return CommandStatus.InvalidControlIP
with TryLock(self._command_lock) as success:
if not success:
return CommandStatus.Blocked
status = self._request_with_status('status')
state = _parse_mountstate(status)
if state == MountState.NotHomed:
return CommandStatus.MountNotHomed
if state == MountState.Parked and not self._set_axis_power(True):
return CommandStatus.Failed
success = self._point('mount/follow_tle', MountState.Tracking,
line1=line1, line2=line2, line3=line3)
return CommandStatus.Succeeded if success else CommandStatus.Failed
@Pyro4.expose
def add_pointing_model_point(self, ra_j2000_deg, dec_j2000_deg):
"""
Add a point to PWI4's pointing model, mapping the current
pointing direction to the specified J2000 coordinates.
"""
if not pyro_client_matches(self._config.control_ips):
return CommandStatus.InvalidControlIP
with TryLock(self._command_lock) as success:
if not success:
return CommandStatus.Blocked
status = self._request_with_status('status')
if _parse_mountstate(status) != MountState.Tracking:
return CommandStatus.Failed
status = self._request_with_status('mount/model/add_point',
ra_j2000_hours=ra_j2000_deg / 15,
dec_j2000_degs=dec_j2000_deg)
return CommandStatus.Failed if status is None else CommandStatus.Succeeded
@Pyro4.expose
def ping(self):
"""Returns immediately with a success status"""
return CommandStatus.Succeeded
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Telescope Server')
parser.add_argument('config', help='Path to configuration json file')
args = parser.parse_args()
c = Config(args.config)
c.daemon.launch(MountDaemon(c))