#!/usr/bin/env python3 """Socket Client Telescope (abstract) implementation To be used as a base class (interface) for any concrete socket client telescope class """ # Standard library imports #from enum import Enum import sys import time # Third party imports # from sockets_tele/ #sys.path.append("..") # from src_socket/client/ sys.path.append("../../../..") #import src.core.pyros_django.utils.celme as celme import vendor.guitastro as guitastro # Local application imports #sys.path.append('../..') #from src.client.socket_client_abstract import UnknownCommandException, SocketClientAbstract ##from src_socket.client.socket_client_abstract import * #from device_controller.abstract_component.device_controller import * from device_controller.abstract_component.device_controller import ( printd, DeviceController, generic_cmd, GenericResult, UnknownNativeCmdException, UnknownNativeResException, UnknownGenericCmdArgException, DeviceTimeoutException, Cmd, Gen2NatCmds ) # Execute also "set" and "do" commands #GET_ONLY=False # Execute only "get" commands #GET_ONLY=True # Default timeouts TIMEOUT_SEND = 10 TIMEOUT_RECEIVE = 10 ''' class c(Enum): # GET, SET DEC = 'DEC' RA = 'RA' RA_DEC = 'RA_DEC' # DO PARK = 'PARK' WARM_START = 'WARM_START' ''' class Position(): x = 0 y = 0 def __init__(self, x,y): self.x = x self.y = y def get_values(self): return self.x, self.y #class SocketClientTelescopeAbstract(SocketClientAbstract): #class TelescopeControllerAbstract(DeviceController): class DC_Mount(DeviceController): # @abstract (to be overriden) _cmd_device_concrete = {} ##_cmd_device_abstract = { GEN2NAT_CMDS_obj = Gen2NatCmds([ # GET-SET commands: # (test only) will raise a NotImplementedException Cmd('do_unimplemented'), Cmd('get_ack'), Cmd('get_ra'), Cmd('set_ra'), Cmd('get_dec'), Cmd('set_dec'), Cmd('get_radec', 'get_radec'), Cmd('set_radec', 'set_radec'), Cmd('get_longitude'), Cmd('set_longitude'), Cmd('get_latitude'), Cmd('set_latitude'), Cmd('get_velocity'), Cmd('set_velocity'), # DO commands: ##'do_init': ['do_init'], ##'do_park': [], Cmd('do_goto','do_goto'), # for test only Cmd('mount_only'), Cmd('do_goto_radec','do_goto_radec'), Cmd('do_move'), Cmd('do_movenorth'), Cmd('do_movesouth'), Cmd('do_movewest'), Cmd('do_moveeast'), Cmd('do_move_dir'), Cmd('do_warm_start'), Cmd('do_prec_refr'), ]) ''' my_cmds2 = Gen2NatCmds() my_cmds2.add_cmds(GEN2NAT_CMDS_obj) ''' ''' print("******************************") print("(MOUNT) Mes commandes") my_cmds2.print_mes_commandes() print("******************************") ''' GEN2NAT_CMDS_dict = { # GET-SET commands: # (test only) will raise a NotImplementedException 'do_unimplemented': [], 'get_ack': [], 'get_ra': [], 'set_ra': [], 'get_dec': [], 'set_dec': [], #'get_radec': [get_radec], 'get_radec': ['get_radec'], 'set_radec': ['set_radec'], 'get_longitude': [], 'set_longitude': [], 'get_latitude': [], 'set_latitude': [], 'get_velocity': [], 'set_velocity': [], # DO commands: ##'do_init': ['do_init'], ##'do_park': [], 'do_goto': ['do_goto'], # for test only 'mount_only':[], 'do_goto_radec': ['do_goto_radec'], 'do_move': [], 'do_movenorth': [], 'do_movesouth': [], 'do_movewest': [], 'do_moveeast': [], 'do_move_dir': [], 'do_warm_start': [], 'do_prec_refr': [], } #GEN2NAT_CMDS = my_cmds2.get_as_dict() GEN2NAT_CMDS = GEN2NAT_CMDS_dict #GEN2NAT_CMDS = Gen2NatCmds(GEN2NAT_CMDS_obj).get_as_dict() GEN2NAT_CMDS = GEN2NAT_CMDS_obj #TODO: remplacer PROTOCOL par "SOCKET-TCP", "SOCKET-UDP", "SERIAL", ou "USB" ##def __init__(self, device_host:str="localhost", device_port:int=11110, PROTOCOL:str="TCP", buffer_size=1024, DEBUG=False, device_sim=None): def __init__(self, device_host:str="localhost", device_port:int=11110, channel:str=None, buffer_size=None, protoc=None, gen2nat_cmds={}, device_sim=None): ''' :param device_host: server IP or hostname :param device_port: server port :param CHANNEL: "UDP" or "TCP" ''' # _my_gen2nat_cmds = GEN2NAT_CMDS + gen2nat_cmds #self._my_gen2nat_cmds = self.GEN2NAT_CMDS #self._my_gen2nat_cmds.update(gen2nat_cmds) #printd("(mount 1) my cmds (before):", self.GEN2NAT_CMDS) #printd("(mount 2) given cmds (before):", gen2nat_cmds) ##self._my_gen2nat_cmds = { **self.GEN2NAT_CMDS, **gen2nat_cmds } #v3 #my_gen2nat_cmds = { **self.GEN2NAT_CMDS, **gen2nat_cmds } #v4 my_gen2nat_cmds = Gen2NatCmds({ **(self.GEN2NAT_CMDS.get_as_dict()), **(gen2nat_cmds.get_as_dict()) }) #print("(mount 3) my cmds (after):", my_gen2nat_cmds) ##super().__init__(device_host, device_port, channel, buffer_size, DEBUG, device_sim) super().__init__(device_host, device_port, channel, buffer_size, protoc=protoc, gen2nat_cmds=my_gen2nat_cmds, device_sim=device_sim) self.printd("IN DC_Mount") # overwrite abstract _cmd dictionary with subclass native _cmd_native dictionary: #self._cmd = {**self._cmd, **self._cmd_native} ##if gen2nat_qa: self._cmd_device_concrete = {**self._cmd_device_concrete, **gen2nat_qa} def get_celme_longitude(self, longitude): return guitastro.Angle(longitude).sexagesimal("d:+0180.0") def get_celme_latitude(self, latitude): return guitastro.Angle(latitude).sexagesimal("d:+090.0") ''' TELESCOPE COMMANDS (abstract methods) ''' ''' **************************** **************************** GENERIC TELESCOPE COMMANDS (abstract methods) **************************** **************************** ''' ''' **************************** GENERIC GET & SET commands **************************** ''' # @abstract @generic_cmd def get_ack(self): pass #return self.execute_generic_cmd("get_ack") # RA/DEC # @abstract ''' Sets the object's Right Ascension and the object status to "Not Selected". The :Sd# command has to follow to complete the selection. The subsequent use of the :ON...# command is recommended (p106) :Sr:.# or :Sr::# 0 if invalid 1 if valid ''' @generic_cmd def get_ra(self): pass #def get_ra(self): return self.execute_generic_cmd("get_ra") @generic_cmd def set_ra(self, ra): pass #return self._set("ra", ra) ''' Sets the object's declination. It is important that the :Sr# command has been send prior. Internal calculations are done that may take up to 0.5 seconds. If the coordinate selection is valid the object status is set to "Selected" :Sd{+-}
{*°}# or :Sd{+- }
{*°:}: 0 if invalid 1 if valid ''' @generic_cmd def get_dec(self): pass #def get_dec(self): return self.execute_generic_cmd("get_dec") @generic_cmd def set_dec(self, dec): pass #def set_dec(self, dec): return self._set("dec", dec) # MACRO radec #def get_radec(self): return self._get("RADEC") #def get_radec(self)->tuple: return ((self.get_ra()), (self.get_dec())) def get_radec(self)->GenericResult: return GenericResult(self.get_ra().txt + "," + self.get_dec().txt) # MACRO def set_radec(self, ra, dec)->GenericResult: self.set_ra(ra) self.set_dec(dec) return GenericResult("OK") @generic_cmd def get_long(self): pass @generic_cmd def set_long(self, longitude): pass @generic_cmd def get_lat(self): pass @generic_cmd def set_lat(self, latitude): pass @generic_cmd def get_vel(self): pass ''' **************************** GENERIC DO commands **************************** ''' # @abstract #def do_INIT(self): return self._do("INIT") ''' do_PARK() (p103) - STARTUP position = CWD - :hC# - position required for a Cold or Warm Start, pointing to the celestial pole of the given hemisphere (north or south), with the counterweight pointing downwards (CWD position). From L4, V1.0 up - HOME position parking => par defaut, c'est CWD, mais ca peut etre different - :hP# - defaults to the celestial pole visible at the given hemisphere (north or south) and can be set by the user ''' @generic_cmd def do_move(self): pass @generic_cmd def do_movenorth(self): pass @generic_cmd def do_movesouth(self): pass @generic_cmd def do_movewest(self): pass @generic_cmd def do_moveeast(self): pass # @abstract #def do_GOTO(self, pos:Position): return self._do("GOTO") #def do_WARM_START(self): return self._do("WARM_START") @generic_cmd def do_warm_start(self): pass @generic_cmd def do_prec_refr(self): pass # MACRO generic command def do_init(self): self.printd("...STARTING TELESCOPE INITIALIZATION...") time.sleep(1) self.printd("...TELESCOPE INITIALIZATION ENDED") return GenericResult("OK") ''' 1) Send cde ACK ('06') and check answer to see if telescope is ready (see doc page 100) (utile pour savoir si tout est ok ; par ex, si une raquette est branchée sur le tele, ça peut bloquer le protocole) Usable for testing the serial link and determining the type of mount (German equatorial). Return code can be: - B# while the initial startup message is being displayed (new in L4), - b# while waiting for the selection of the Startup Mode, - S# during a Cold Start (new in L4), - G# after completed startup ==> MEANS ALL IS OK ''' #ACK = self.get("ACK") ACK = self.get_ack() ''' 2) IF telescope is not ready (still starting up), ask it to do a Warm Start ('bW#') During Startup, with a "b#" being returned, the PC can select the startup mode by sending a • bC# for selecting the Cold Start, • bW# for selecting the Warm Start, • bR# for selecting the Warm Restart If not ok (still starting up, no 'G#' in return), send 'bW#' (see above) for selecting the Warm Start ''' #if ACK != 'G': if not ACK.ok: self.do_warm_start() ACK = self.get_ack() elapsed_time = 0 while not ACK.ok: time.sleep(1) elapsed_time += 1 if elapsed_time == TIMEOUT_RECEIVE: raise TimeoutException() ACK = self.get_ack() ''' 3) Set timezone, date, and time (p109) ''' ''' a) set TIMEZONE Set the number of hours by which your local time differs from UTC. If your local time is earlier than UTC set a positive value, if later than UTC set a negative value. The time difference has to be set before setting the calendar date (SC) and local time (SL), since the Real Time Clock is running at UTC => :SG{+-}hh# ''' res = self.get_timezone() self.printd("Current timezone is", res) res = self.set_timezone('+00') #if res != '1': raise UnknownNativeResException(res) if not res.ok: raise UnknownNativeResException(res) res = self.get_timezone() if res.txt != '+00': raise UnknownNativeResException(res) self.printd("NEW timezone set is", res) ''' b) set DATE Set Calendar Date: months mm, days dd, year yy of the civil time according to the timezone set. The internal calendar/clock uses GMT :SC/
/# 0 if invalid or TODO: 1Updating planetary data#<24 blanks># ''' res = self.get_date() self.printd("Current date is", res) # format is 2018-09-26T17:50:21 d = self.get_utc_date() # format to mm/dd/yy now_utc_mm_dd_yy = d[5:7] + '/' + d[8:10] + '/' + d[2:4] #printd("date is", now_utc_mm_dd_yy) res = self.set_date(now_utc_mm_dd_yy) #res = self.set_DATE(self.get_utc_date()) #if res[0] != '1': raise UnknownNativeResException(res) #if not res.startswith('1Updating planetary data'): raise UnknownNativeResException(res) if not res.ok: raise UnknownNativeResException(res) res = self.get_date() if res.txt != now_utc_mm_dd_yy: raise UnknownNativeResException(res) self.printd("NEW DATE set is", res) ''' c) set TIME Set RTC Time from the civil time hours hh, minutes mm and seconds ss. The timezone must be set before using this command :SL::# ''' res = self.get_time() self.printd("Current time is", res) _,now_utc_hh_mm_ss = d.split('T') #printd("time is", now_utc_hh_mm_ss[:5]) res = self.set_time(now_utc_hh_mm_ss) #if res != '1': raise UnknownNativeResException(res) if not res.ok: raise UnknownNativeResException(res) res = self.get_time() if res.txt[:5] != now_utc_hh_mm_ss[:5]: raise UnknownNativeResException(res) self.printd("NEW TIME set is", res) ''' 4) Set LOCATION (lat,long) (p103,110) Pour l'observatoire de Guitalens: Sg = 2.0375 E St = 43.6443 N (attention, 2.0375 E = - 2.0375) ''' ''' a) set Longitude Sets the longitude of the observing site to ddd degrees and mm minutes. The longitude has to be specified positively for western latitudes (west of Greenwich, the plus sign may be omitted) and negatively for eastern longitudes. Alternatively, 360 degrees may be added to eastern longitudes. => :Sg{+-}*# ''' # TELE format is -002°02 (I convert it to -002:02) res = self.get_long() self.printd("Current longitude is", res) # CELME format is -002:02:15 res = self.get_celme_longitude("-2.0375") res_ddd_mm = res[:-3] #res_ddd_mm = res[:-3].replace(':','*') #res_ddd_mm = '-002:03' #printd("celme longitude is", res) ddd,mm,ss = res.split(':') #dddmm = '-002*03' res = self.set_long(ddd+'*'+mm) #if res != '1': raise UnknownNativeResException(res) if not res.ok: raise UnknownNativeResException(res) res = self.get_long() if res.txt != res_ddd_mm: raise UnknownNativeResException(res_ddd_mm, res.txt) self.printd("NEW longitude set is", res) ''' b) set Latitude Sets the latitude of the observing site to dd degrees, mm minutes. The minus sign indicates southern latitudes, the positive sign may be omitted. => :St{+-}
*# ''' # TELE format is +43°38 (I convert it to +43:38) res = self.get_lat() self.printd("Current latitude is", res) # CELME format is +43:38:15 res = self.get_celme_latitude("+43.6443") res_dd_mm = res[:-3] #res_dd_mm = res[:-3].replace(':','*') self.printd("res is", res) #res_dd_mm = '+43:50' #printd("celme longitude is", res) dd,mm,ss = res.split(':') ddmm = dd+'*'+mm #ddmm = '+43*50' res = self.set_lat(ddmm) #if res != '1': raise UnknownNativeResException(res) if not res.ok: raise UnknownNativeResException(res) res = self.get_lat() if res.txt != res_dd_mm: raise UnknownNativeResException(res_dd_mm,res.txt) self.printd("NEW latitude set is", res) ''' 5) Send cde ':p3#' : Precession & Refraction (see page 107) Ask Gemini to do Precession calculation Coordinates transferred to the Gemini refer to the standard epoch J2000.0. Refraction is calculated (From L4, V1.0 up) ''' self.do_prec_refr() return GenericResult("OK") # @abstract def set_speed(self, speed_rate): pass ''' GOTO (p105) - GOTO(position, blocking=Y/N): (MS = move start) = Goto RA=18h23m45s Dec=+34d00m00s J2000 - radec.goto() ''' # MACRO generic command def do_goto_radec(self, ra, dec, speed_rate=None): return self.do_goto(ra, dec, speed_rate) def do_goto(self, ra, dec, speed_rate=None): # TODO: remove self.printd("...Starting GOTO...") time.sleep(3) radec = self.get_radec() self.printd("...GOTO ended OK") return GenericResult("OK") # 1) set speed if speed_rate : self.set_speed(speed_rate) radec = self.get_radec() self.printd("Current position is", radec) # 2) set RA-DEC ''' :Sr18:23:45#:Sd+34:00:00#:MS# ''' res = self.set_ra(ra) #if res != '1': raise UnknownNativeResException(res) ##if res.ko: raise UnknownNativeResException(res) if res.unknown_command: raise UnknownNativeCmdException("set_ra") if res.unknown_result: raise UnknownNativeResException(res.txt) res = self.set_dec(dec) #if res != '1': raise UnknownNativeResException(res) ##if res.ko: raise UnknownNativeResException(res) if res.unknown_result: raise UnknownNativeResException(res) # 3) MOVE (non blocking by default for Gemini) self.do_move() # 4) Test velocity until it is "Tracking" ''' After MOVE, test velocity with ':Gv#' (p103) : we should have 'S', then 'C', then 'T' - N (for "no tracking") - T (for Tracking) - G (for Guiding) - C (for Centering) - S (for Slewing) ''' vel = None while vel != 'T': v = self.get_vel() vel = v.txt self.printd("Velocity is", v) time.sleep(2) time.sleep(2) radec= self.get_radec() self.printd("Current position is", radec) return GenericResult("OK") # @abstract MACRO def do_move_dir(self, dir, nbsec, speed_rate=None): dir = dir.upper() if speed_rate: self.set_speed(speed_rate) if dir=="NORTH": self.do_movenorth() elif dir=="SOUTH": self.do_movesouth() elif dir=="WEST": self.do_movewest() elif dir=="EAST": self.do_moveeast() else: raise UnknownGenericCmdArgException(dir) time.sleep(int(nbsec)) self.do_stop() return GenericResult("OK") # TODO: empecher de creer une instance de cette classe abstraite # Avec ABC ? ''' if __name__ == "__main__": #HOST, PORT = "localhost", 9999 #HOST, PORT = "localhost", 20001 HOST, PORT = "localhost", 11110 # Classic usage: #tsock = SocketClient_UDP_TCP(HOST, PORT, "UDP") # More elegant usage, using "with": with SocketClient_ABSTRACT(HOST, PORT, "UDP") as tsock: # 0) CONNECT to server (only for TCP, does nothing for UDP) tsock._connect_to_server() while True: # 1) SEND REQUEST data to server # saisie de la requête au clavier et suppression des espaces des 2 côtés data = input("REQUEST TO SERVER [ex: ':GD#' (Get Dec), ':GR#' (Get RA)']: ").strip() # test d'arrêt if data=="": break #data_to_send = bytes(data + "\n", "utf-8") tsock.send_data(data) #mysock.sendto("%s" % data, (HOST, PORT)) #printd("Sent: {}".format(data)) # 2) RECEIVE REPLY data from server data_received = tsock.receive_data() #reponse, adr = mysock.recvfrom(buf) #printd("Received: {}".format(data_received)) #printd("Useful data received: {}".format(data_useful)) printd('\n') #tsock.close() '''