-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmeade_mountd
executable file
·861 lines (699 loc) · 33.3 KB
/
meade_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
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
#!/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 16" Meade LX200-GPS via Pyro"""
import argparse
import queue
import re
import sys
import threading
import time
import traceback
from astropy.coordinates import AltAz, Angle, FK5, ICRS, SkyCoord, EarthLocation, get_moon, get_sun
from astropy.time import Time
import astropy.units as u
import serial
import Pyro4
from rockit.common import log, TryLock
from rockit.common.helpers import pyro_client_matches
from rockit.mount.meade import CommandStatus, Config, TelescopeState
SEXAGESIMAL_REGEX = re.compile(rb'^(?P<unit>[+-]?\d+)(?P<type>[:\xDF])(?P<minutes>\d+):(?P<seconds>\d+)$')
def command_without_response(port, command):
port.flushInput()
port.write(f':{command}#'.encode('ascii'))
def command_with_response(port, command, response_length):
port.flushInput()
port.write(f':{command}#'.encode('ascii'))
return port.read(response_length)
def command_with_bool_response(port, command):
port.flushInput()
port.write(f':{command}#'.encode('ascii'))
while True:
char = port.read(1)
if char == b'\x15':
# Telescope is busy, wait and retry
time.sleep(1)
print(f'DEBUG: retrying :{command}#')
port.write(f':{command}#'.encode('ascii'))
else:
return char == b'1'
def command_with_string_response(port, command):
port.flushInput()
port.write(f':{command}#'.encode('ascii'))
response = []
while True:
char = port.read(1)
if char == b'\x15' and not response:
# Telescope is busy, wait and retry
time.sleep(1)
print(f'DEBUG: retrying :{command}#')
port.write(f':{command}#'.encode('ascii'))
if char == b'#':
return b''.join(response)
response.append(char)
def sexagesimal_to_degrees(source):
match = SEXAGESIMAL_REGEX.match(source)
if not match:
raise ValueError(f'{source} is not a sexagesimal string')
unit = float(match.group('unit'))
sign = -1 if match.group('unit')[0:1] == b'-' else 1
value = unit + sign * float(match.group('minutes')) / 60. + sign * float(match.group('seconds')) / 3600.
if match.group('type') == b':':
value *= 15
return value
class MeadeDaemon:
"""Daemon interface for talon subsystems"""
def __init__(self, config):
self._config = config
self._location = EarthLocation(
lat=config.latitude*u.deg,
lon=config.longitude*u.deg,
height=config.altitude*u.m)
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._initializing = False
self._force_stopped = False
self._command_lock = threading.Lock()
self._comm_lock = threading.Lock()
self._command_queue = queue.Queue()
self._result_queue = queue.Queue()
self._move_complete_condition = threading.Condition()
self._port = None
self._state_lock = threading.Lock()
self._current_state = None
threading.Thread(target=self.__run, daemon=True).start()
def _initialize(self):
"""
Opens the serial connection and negotiate initialization handshake
This may take a minute or two to return.
Returns CommandStatus reflecting result
"""
if self._port is not None:
return CommandStatus.NotDisconnected
try:
self._initializing = True
port = serial.Serial(self._config.serial_port,
self._config.serial_baud,
timeout=self._config.serial_timeout)
log.info(self._config.log_name, 'connected to mount')
# Flush any stale state
port.flushInput()
port.flushOutput()
# Reboot mount
print('Rebooting mount')
command_without_response(port, 'I')
# Wait for mount to respond
initialize_start = Time.now()
while True:
port.flushInput()
port.flushOutput()
port.write(b'\x06')
response = port.read(1)
if len(response) > 0:
if response not in [b'L', b'P']:
raise ValueError('Mount is not in Polar mode')
break
if (Time.now() - initialize_start) > self._config.initialize_timeout * u.s:
raise serial.SerialException('Mount initialization timed out')
time.sleep(5)
time.sleep(1)
port.flushInput()
print('Connected to mount')
# Wait for worm gear to find its home position
print('Waiting for Smart Drive to initialize')
while True:
if (Time.now() - initialize_start) > self._config.initialize_timeout * u.s:
raise serial.SerialException('Mount initialization timed out')
if b'Smart Drive' not in command_with_string_response(port, 'ED'):
break
time.sleep(5)
# Send current time (bypasses the daylight savings prompt on the hand box)
# Note that this isn't applied until after the Smart Drive has initialized
ret = command_with_bool_response(port, f'hI{Time.now().strftime("%y%m%d%H%M%S")}')
if not ret:
raise serial.SerialException('Failed to set current time')
print('Waiting for mount to home')
while True:
if (Time.now() - initialize_start) > self._config.initialize_timeout * u.s:
raise serial.SerialException('Mount initialization timed out')
if b'Finding Home' not in command_with_string_response(port, 'ED'):
break
time.sleep(5)
# Validate site location and time
latitude = sexagesimal_to_degrees(command_with_string_response(port, 'Gt'))
latitude_delta = latitude - self._location.lat.to_value(u.deg)
# Note: Mount returns western longitudes as positive(!)
longitude = -sexagesimal_to_degrees(command_with_string_response(port, 'Gg'))
longitude_delta = longitude - self._location.lon.to_value(u.deg)
lst = sexagesimal_to_degrees(command_with_string_response(port, 'GS')) * u.deg
lst_delta = ((lst - Time(Time.now(), location=self._location).sidereal_time('apparent'))
.wrap_at(180*u.deg)).to_value(u.deg)
if abs(latitude_delta) > 0.5:
raise ValueError(f'Latitude does not match expected site location (delta is {latitude_delta} deg)')
if abs(longitude_delta) > 0.5:
raise ValueError(f'Longitude does not match expected site location (delta is {longitude_delta} deg)')
if abs(lst_delta) > 0.16667:
raise ValueError(f'LST does not match expected site location (delta is {lst_delta} deg)')
self._port = port
self._set_tracking(False)
# Refresh state before considering the connection valid
self._update_state()
log.info(self._config.log_name, 'initialization complete')
return CommandStatus.Succeeded
except Exception as e:
print('Failed to communicate with telescope')
traceback.print_exc(file=sys.stdout)
if self._port is not None:
self._port.close()
self._port = None
print('is valueerror', isinstance(e, ValueError))
return CommandStatus.InvalidMountConfiguration if isinstance(e, ValueError) else CommandStatus.Failed
finally:
self._initializing = False
def _set_tracking(self, enabled):
# Enable or disable sidereal tracking
# by switching the mount between Polar and Land mode.
# This may take multiple attempts to succeed
desired = b'T' if enabled else b'N'
command = 'AP' if enabled else 'AL'
while True:
alignment = command_with_response(self._port, 'GW', 3)
if alignment[1:2] == desired:
break
command_without_response(self._port, command)
time.sleep(1)
def _shutdown(self):
"""
Sends a telescope park command and closes the serial connection
Returns CommandStatus reflecting result
"""
with self._state_lock:
if self._port is None:
return CommandStatus.NotConnected
try:
if self._port is not None:
# Slew to park position so mount remembers position
command_without_response(self._port, 'hP')
self._port.close()
self._port = None
return CommandStatus.Succeeded
except Exception as exception:
print(f'Failed to close serial port ({exception})')
self._port = None
return CommandStatus.Failed
def _update_state(self):
"""Request and parse telescope state"""
data = None
state = TelescopeState.Disabled
if self._port is not None:
update_time = Time.now()
while True:
alt_str = command_with_string_response(self._port, 'GA')
if alt_str:
break
time.sleep(1)
alt = sexagesimal_to_degrees(alt_str)
az = sexagesimal_to_degrees(command_with_string_response(self._port, 'GZ'))
lst = sexagesimal_to_degrees(command_with_string_response(self._port, 'GS'))
if command_with_string_response(self._port, 'D'):
state = TelescopeState.Slewing
# Reported RA,Dec are incorrect when slewing, so calculate from Alt, Az
coords_j2000 = SkyCoord(alt=alt, az=az, unit=u.deg, frame='altaz',
location=self._location, obstime=update_time).icrs
coords_jnow = coords_j2000.transform_to(FK5(equinox=update_time))
else:
alignment = command_with_response(self._port, 'GW', 3)
state = TelescopeState.Tracking if alignment[1:2] == b'T' else TelescopeState.Stopped
while True:
ra_str = command_with_string_response(self._port, 'GR')
if ra_str:
break
time.sleep(1)
ra_jnow = sexagesimal_to_degrees(ra_str)
dec_jnow = sexagesimal_to_degrees(command_with_string_response(self._port, 'GD'))
coords_jnow = SkyCoord(ra=ra_jnow, dec=dec_jnow, unit=u.deg, frame=FK5(equinox=update_time))
coords_j2000 = coords_jnow.transform_to(ICRS)
data = {
'date': update_time.strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
'state': state,
'state_label': TelescopeState.label(state),
'lst': lst,
'ra': coords_j2000.ra.to_value(u.deg),
'ha': lst - coords_jnow.ra.to_value(u.deg),
'dec': coords_j2000.dec.to_value(u.deg),
'alt': alt,
'az': az,
'site_latitude': self._location.lat.to_value(u.deg),
'site_longitude': self._location.lon.to_value(u.deg),
'site_elevation': self._location.height.to_value(u.m),
'moon_separation': get_moon(update_time).separation(coords_j2000).to_value(u.deg),
'sun_separation': get_sun(update_time).separation(coords_j2000).to_value(u.deg),
}
with self._state_lock:
was_slewing = False
if self._current_state is not None:
was_slewing = self._current_state['state'] == TelescopeState.Slewing
is_slewing = state == TelescopeState.Slewing
self._current_state = data
if was_slewing and not is_slewing:
with self._move_complete_condition:
self._move_complete_condition.notify_all()
def process_request(self, request, data):
"""
Process a command sent by the user
Returns a CommandStatus that is pushed to the results queue
"""
if self._port is None:
return CommandStatus.NotConnected
if request == 'stop':
if self._config.dome_daemon:
try:
with self._config.dome_daemon.connect() as ops:
ops.notify_telescope_stopped()
except Exception as e:
log.error(self._config.log_name, 'Failed to notify dome daemon (' + str(e) + ')')
sys.stdout.flush()
self._force_stopped = True
command_without_response(self._port, 'Q')
time.sleep(1)
self._set_tracking(False)
with self._move_complete_condition:
self._move_complete_condition.notify_all()
elif request == 'track':
coords = data.transform_to(FK5(equinox=data.obstime))
ra = coords.ra.to(u.hourangle).to_string(sep=":", precision=0, pad=True)
dec = coords.dec.to(u.deg).to_string(sep="*:", precision=0, alwayssign=True, pad=True)
if self._config.dome_daemon:
try:
with self._config.dome_daemon.connect() as ops:
ops.notify_telescope_radec(data.ra.to_value(u.deg), data.dec.to_value(u.deg), True)
except Exception as e:
log.error(self._config.log_name, 'Failed to notify dome daemon (' + str(e) + ')')
sys.stdout.flush()
if not command_with_bool_response(self._port, f'Sr{ra}'):
return CommandStatus.Failed
if not command_with_bool_response(self._port, f'Sd{dec}'):
return CommandStatus.Failed
# Slew to target coordinates with sidereal tracking
ret = command_with_response(self._port, 'MS', 1)
if ret != b'0':
self._port.read_until('#')
return CommandStatus.Failed
return CommandStatus.Succeeded
elif request in ['slew', 'park']:
# 'MA' command assumes that the telescope is mounted altaz
# For an equatorial mount this maps from
# Altitude -> Dec
# Azimuth -> 180 + HA
# Adjust coordinates to suit
coords = data.transform_to(FK5(equinox=data.obstime))
alt = coords.dec.to(u.deg).to_string(sep="*'", precision=0, alwayssign=True, pad=True)
lst = Time(data.obstime, location=data.location).sidereal_time('apparent')
az = (180 * u.deg + lst - coords.ra.to(u.deg)).wrap_at(360 * u.deg).to_value(u.deg)
az_deg = int(az)
az_min = int(60*(az - az_deg))
if self._config.dome_daemon:
try:
with self._config.dome_daemon.connect() as ops:
if request == 'park':
ops.notify_telescope_parked()
elif isinstance(data.frame, AltAz):
ops.notify_telescope_altaz(data.alt.to_value(u.deg), data.az.to_value(u.deg))
else:
ops.notify_telescope_radec(data.ra.to_value(u.deg), data.dec.to_value(u.deg), False)
except Exception as e:
log.error(self._config.log_name, 'Failed to notify dome daemon (' + str(e) + ')')
sys.stdout.flush()
if not command_with_bool_response(self._port, f'Sa{alt}'):
return CommandStatus.Failed
if not command_with_bool_response(self._port, f'Sz{az_deg:03d}*{az_min:02d}'):
return CommandStatus.Failed
# Slew to target coordinates
ret = command_with_response(self._port, 'MA', 1)
if ret != b'0':
return CommandStatus.Failed
return CommandStatus.Succeeded
elif request == 'offset_radec':
ra_delta_deg, dec_delta_deg = data
# Only support offsets less than an arcminute
# Larger offsets should issue a slew / track command
if abs(ra_delta_deg * 60) > 1 or abs(dec_delta_deg * 60) > 1:
return CommandStatus.Failed
# Set offset rate to 10 arcsec/sec
command_without_response(self._port, 'Rg10.0')
command_without_response(self._port, 'RG')
ra_millis = int(ra_delta_deg * 360000)
if ra_millis > 0:
command_without_response(self._port, f'Mge{ra_millis:04d}')
elif ra_millis < 0:
command_without_response(self._port, f'Mgw{-ra_millis:04d}')
dec_millis = int(dec_delta_deg * 360000)
if dec_millis > 0:
command_without_response(self._port, f'Mgn{dec_millis:04d}')
elif dec_millis < 0:
command_without_response(self._port, f'Mgs{-dec_millis:04d}')
return CommandStatus.Succeeded
elif request == 'sync':
coords = data.transform_to(FK5(equinox=Time.now()))
ra = coords.ra.to(u.hourangle).to_string(sep=":", precision=0, pad=True)
dec = coords.dec.to(u.deg).to_string(sep="*:", precision=0, alwayssign=True, pad=True)
if not command_with_bool_response(self._port, f'Sr{ra}'):
return CommandStatus.Failed
if not command_with_bool_response(self._port, f'Sd{dec}'):
return CommandStatus.Failed
# Sync to target coordinates
ret = command_with_string_response(self._port, 'CM')
if ret != b" M31 EX GAL MAG 3.5 SZ178.0'":
return CommandStatus.Failed
elif request == 'zero':
# Set target coordinates to match the zero markers (HA = DEC = 0)
lst = Angle((self._current_state['lst'] * u.deg).to(u.hourangle)).to_string(sep=":", precision=0, pad=True)
if not command_with_bool_response(self._port, f'Sr{lst}'):
return CommandStatus.Failed
if not command_with_bool_response(self._port, 'Sd+00*00:00'):
return CommandStatus.Failed
# Sync to target coordinates
ret = command_with_string_response(self._port, 'CM')
if ret != b" M31 EX GAL MAG 3.5 SZ178.0'":
return CommandStatus.Failed
# Sidereal tracking restarts a few seconds after syncing
time.sleep(5)
self._set_tracking(False)
# Set park position
command_without_response(self._port, 'hS')
log.info(self._config.log_name, 'mount zeroed')
else:
print(f'Unknown request `{request}`')
return CommandStatus.Failed
return CommandStatus.Succeeded
def __run(self):
"""Background thread managing communication over the serial connection"""
delay = self._config.idle_loop_delay
while True:
try:
request, data = self._command_queue.get(timeout=delay)
except queue.Empty:
request, data = None, None
if request == 'initialize':
self._result_queue.put(self._initialize())
continue
if request == 'shutdown':
self._result_queue.put(self._shutdown())
continue
result = CommandStatus.NotConnected
try:
self._update_state()
if request is not None:
result = self.process_request(request, data)
self._update_state()
if self._current_state and self._current_state['state'] == TelescopeState.Slewing:
delay = self._config.slew_loop_delay
else:
delay = self._config.idle_loop_delay
except Exception as exception:
with self._state_lock:
if self._port is not None:
self._port.close()
self._port = None
print(f'Failed to issue command ({exception})')
log.error(self._config.log_name, 'Lost serial connection')
traceback.print_exc(file=sys.stdout)
finally:
if request is not None:
self._result_queue.put(result)
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
@Pyro4.expose
def report_status(self):
"""Returns a dictionary containing the current telescope state"""
with self._state_lock:
data = self._current_state
if data is None:
state = TelescopeState.Initializing if self._initializing else TelescopeState.Disabled
data = {
'date': Time.now().strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
'state': state,
'state_label': TelescopeState.label(state)
}
return data
@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
with self._comm_lock:
self._command_queue.put(('initialize', None))
return self._result_queue.get()
@Pyro4.expose
def stop(self):
"""Stops any active telescope movement"""
if not pyro_client_matches(self._config.control_ips):
return CommandStatus.InvalidControlIP
with self._state_lock:
if self._current_state is None:
return CommandStatus.NotConnected
with self._comm_lock:
self._command_queue.put(('stop', None))
self._result_queue.get()
# Block until any other pointing commands have terminated before cleaning up
with self._command_lock:
self._force_stopped = False
return CommandStatus.Succeeded
def _point(self, coords, tracking=False, parking=False):
"""Moves the telescope to a specified SkyCoord and optionally begins tracking"""
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
with self._state_lock:
if self._current_state is None:
return CommandStatus.NotConnected
with self._comm_lock:
if tracking:
command = 'track'
elif parking:
command = 'park'
else:
command = 'slew'
self._command_queue.put((command, coords))
status = self._result_queue.get()
if status != CommandStatus.Succeeded:
return status
start = Time.now()
with self._move_complete_condition:
while True:
# Note: it can take a second before the slew begins
# Wait an interval period so we don't exit too early
self._move_complete_condition.wait(self._config.slew_loop_delay)
if self._force_stopped:
break
with self._state_lock:
if self._current_state.get('state', TelescopeState.Disabled) != TelescopeState.Slewing:
break
if (Time.now() - start).to_value(u.s) > self._config.slew_timeout:
break
if self._force_stopped:
log.error(self._config.log_name, 'Pointing failed: aborted')
return CommandStatus.Failed
return CommandStatus.Succeeded
@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"""
coords = SkyCoord(
ra=ra_deg * u.deg,
dec=dec_deg * u.deg,
frame='icrs',
obstime=Time(Time.now(), location=self._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
return self._point(coords, True)
@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
command = ('offset_radec', (ra_delta_deg, dec_delta_deg))
with self._state_lock:
if self._current_state is None:
return CommandStatus.NotConnected
if abs(ra_delta_deg * 60) >= 1 or abs(dec_delta_deg * 60) >= 1:
# Offsets of 1 arcmin or larger are treated as a regular slew
if self._current_state['state'] == TelescopeState.Tracking:
command = ('track', SkyCoord(
ra=self._current_state['ra'] + ra_delta_deg,
dec=self._current_state['dec'] + dec_delta_deg,
unit=u.deg,
frame='icrs',
obstime=Time(Time.now(), location=self._location)))
else:
now = Time.now()
coords = SkyCoord(
alt=self._current_state['alt'],
az=self._current_state['az'],
unit=u.deg,
frame='altaz',
location=self._location,
obstime=now).icrs
command = ('slew', SkyCoord(
ra=coords.ra + ra_delta_deg * u.deg,
dec=coords.dec + dec_delta_deg * u.deg,
frame='icrs',
obstime=Time(now, location=self._location)))
with self._comm_lock:
self._command_queue.put(command)
status = self._result_queue.get()
if status != CommandStatus.Succeeded:
return status
start = Time.now()
with self._move_complete_condition:
while True:
# Note: it can take a second before the slew begins
# Wait an interval period so we don't exit too early
self._move_complete_condition.wait(self._config.slew_loop_delay)
if self._force_stopped:
break
with self._state_lock:
if self._current_state.get('state', TelescopeState.Disabled) != TelescopeState.Slewing:
break
if (Time.now() - start).to_value(u.s) > self._config.slew_timeout:
break
if self._force_stopped:
log.error(self._config.log_name, 'Pointing failed: aborted')
return CommandStatus.Failed
return CommandStatus.Succeeded
@Pyro4.expose
def slew_radec(self, ra_deg, dec_deg):
"""Moves the telescope to a specified J2000 ra, dec"""
coords = SkyCoord(
ra=ra_deg * u.deg,
dec=dec_deg * u.deg,
frame='icrs',
obstime=Time(Time.now(), location=self._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
return self._point(coords, False)
@Pyro4.expose
def slew_altaz(self, alt_deg, az_deg):
"""Moves the telescope to a specified alt, az"""
coords = SkyCoord(
alt=alt_deg,
az=az_deg,
unit=u.deg,
frame='altaz',
location=self._location,
obstime=Time.now())
# Check against telescope limits
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
return self._point(coords, False)
@Pyro4.expose
def sync(self, ra_deg, dec_deg):
"""Sync the telescope position on a sky 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
with self._state_lock:
if self._current_state is None:
return CommandStatus.NotConnected
with self._comm_lock:
self._command_queue.put(('sync', SkyCoord(ra=ra_deg, dec=dec_deg, unit=u.deg)))
return self._result_queue.get()
@Pyro4.expose
def zero(self):
"""Sync the telescope position on the zero markers"""
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
with self._state_lock:
if self._current_state is None:
return CommandStatus.NotConnected
with self._comm_lock:
self._command_queue.put(('zero', None))
return self._result_queue.get()
@Pyro4.expose
def park(self, position):
"""Moves the telescope to a named park position (but does not disconnect)"""
park = self._config.park_positions.get(position, None)
if park is None:
return CommandStatus.UnknownParkPosition
coords = SkyCoord(
alt=park['alt'],
az=park['az'],
unit=u.deg,
frame='altaz',
location=self._location,
obstime=Time.now())
return self._point(coords, parking=True)
@Pyro4.expose
def train_ra_pec(self, enable):
"""Enables or disables the periodic error correction training mode for the RA axis"""
# TODO
return CommandStatus.Failed
@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
with self._comm_lock:
self._command_queue.put(('shutdown', None))
return self._result_queue.get()
@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(MeadeDaemon(c))