def slew(self): slewFunction = None target = None currentPage = self.module.view.slewOptions.get_current_page() if currentPage == 0: raHour = self.module.view.raHourSpin.get_value() raMinute = self.module.view.raMinuteSpin.get_value() raSec = self.module.view.raSecSpin.get_value() decDegree = self.module.view.decDegreeSpin.get_value() decMinute = self.module.view.decMinuteSpin.get_value() decSec = self.module.view.decSecSpin.get_value() ra = "%2d:%2d:%2d" %(raHour, raMinute, raSec) dec = "%2d:%2d:%2d" %(decDegree, decMinute, decSec) epochStr = str(self.module.view.epochCombo.child.get_text()).lower() if epochStr == "j2000": epoch = Epoch.J2000 elif epochStr == "b1950": epoch = Epoch.B1950 elif epochStr == "now": epoch = Epoch.Now else: # FIXME epoch = epochStr target = Position.fromRaDec(ra, dec, epoch=epoch) slewFunction = self.telescope.slewToRaDec elif currentPage == 1: altDegree = self.module.view.altDegreeSpin.get_value() altMinute = self.module.view.altMinuteSpin.get_value() altSec = self.module.view.altSecSpin.get_value() azDegree = self.module.view.azDegreeSpin.get_value() azMinute = self.module.view.azMinuteSpin.get_value() azSec = self.module.view.azSecSpin.get_value() alt = "%2d:%2d:%2d" %(altDegree, altMinute, altSec) az = "%2d:%2d:%2d" %(azDegree, azMinute, azSec) target = Position.fromAltAz(alt, az) slewFunction = self.telescope.slewToAltAz elif currentPage == 2: target = str(self.module.view.objectNameCombo.child.get_text()) slewFunction = self.telescope.slewToObject self.module.view.slewBeginUi() try: slewFunction(target) except ObjectNotFoundException, e: self.module.view.showError("Object %s was not found on our catalogs." % target)
def syncWithTel(self): self.syncBegin() self.log.debug('[sync] Check if dome is in sync with telescope') if self.getMode() == Mode.Track: self.log.warning('Dome is in track mode... Slew is completely controled by AsTelOS...' 'Waiting for dome to reach expected position') start_time = time.time() tpl = self.getTPL() ref_altitude = Coord.fromD(0.) target_az = Coord.fromD(tpl.getobject('POSITION.INSTRUMENTAL.DOME[0].TARGETPOS')) target_position = Position.fromAltAz(ref_altitude, target_az) while True: current_az = self.getAz() current_position = Position.fromAltAz(ref_altitude, current_az) self.log.debug('Current az: %s | Target az: %s' % (current_az.toDMS(), target_az.toDMS())) if time.time() > (start_time + self._maxSlewTime): if abs(target_position.angsep(current_position).D) < tpl.getobject( 'POINTING.SETUP.DOME.MAX_DEVIATION') * 4.0: self.log.warning("[sync] Dome too far from target position!") break else: self.syncComplete() raise AstelcoDomeException("Dome synchronization timed-out") elif abs(target_position.angsep(current_position).D) < tpl.getobject( 'POINTING.SETUP.DOME.MAX_DEVIATION') * 2.0: break self.syncComplete() self.log.debug('[sync] Dome in sync')
def worldAt(self, *pixel): if not self._findWCS(): return Position.fromRaDec(0, 0) world = self._valueAt(self._wcs.wcs_pix2world, *pixel) return Position.fromRaDec(Coord.fromD(world[0]), Coord.fromD(world[1]))
def _moveScope(self, tracking=False, pierSide=None): """ Moves the scope, usually to zenith """ tel = self._getTel() site = self._getSite() self.log.debug('Moving scope to alt %s az %s.' % (self["flat_alt"], self["flat_az"])) if tel.getPositionAltAz().angsep( Position.fromAltAz(Coord.fromD(self["flat_alt"]), Coord.fromD(self["flat_az"]))).D < self[ "flat_position_max"]: self.log.debug( 'Telescope is less than {} degrees from flat position. Not moving!'.format(self["flat_position_max"])) if tracking and not tel.isTracking(): tel.startTracking() elif not tracking and tel.isTracking(): tel.stopTracking() if pierSide is not None and tel.features(TelescopePier): self.log.debug("Setting telescope pier side to %s." % tel.getPierSide().__str__().lower()) tel.setSideOfPier(self['pier_side']) return try: self.log.debug("Skyflat Slewing scope to alt {} az {}".format(self["flat_alt"], self["flat_az"])) tel.slewToRaDec(Position.altAzToRaDec(Position.fromAltAz(Coord.fromD(self["flat_alt"]), Coord.fromD(self["flat_az"])), site['latitude'], site.LST())) if tracking: self._startTracking() else: self._stopTracking() except: self.log.debug("Error moving the telescope")
def test_distances(self): p1 = Position.fromRaDec("10:00:00", "0:0:0") p2 = Position.fromRaDec("12:00:00", "0:0:0") d = p1.angsep(p2) assert p1.within(p2, Coord.fromD(29.99)) == False assert p1.within(p2, Coord.fromD(30.01)) == True
def computeExtinctionWithLST(self,flux, lstArr): altArr = [] aTuple = self.ra, self.dec raDec = Position(aTuple) for lst in lstArr: #this returns the altitude and azimuth altAz = raDec.raDecToAltAz(raDec, self.latitude, lst) #Get the altitude altArr.append(altAz.alt) print flux print altArr return self.computeExtinctionCoefficient(flux, altArr)
def test_altAzRaDec(self): altAz = Position.fromAltAz('20:30:40', '222:11:00') lat = Coord.fromD(0) o = ephem.Observer() o.lat = '0:0:0' o.long = '0:0:0' o.date = dt.now(tz.tzutc()) lst = float(o.sidereal_time()) raDec = Position.altAzToRaDec(altAz, lat, lst) altAz2 = Position.raDecToAltAz(raDec, lat, lst) assert equal(altAz.alt.toR(),altAz2.alt.toR()) & equal(altAz.az.toR(),altAz2.az.toR())
def park(self): if self.isParked(): return True # 1. slew to park position FIXME: allow different park # positions and conversions from ra/dec -> az/alt site = self.getManager().getProxy("/Site/0") self.slewToRaDec( Position.fromRaDec(str(self.getLocalSiderealTime()), site["latitude"])) # 2. stop tracking self.stopTracking() # 3. power off #self.powerOff () self._parked = True self.parkComplete() return True
def slewToAltAz(self, position): if not isinstance(position, Position): position = Position.fromAltAz(*position) self.slewBegin(self._getSite().altAzToRaDec(position)) alt_steps = position.alt - self.getAlt() alt_steps = float(alt_steps/10.0) az_steps = position.az - self.getAz() az_steps = float(az_steps/10.0) self._slewing = True self._abort.clear() status = TelescopeStatus.OK t = 0 while t < 5: if self._abort.isSet(): self._slewing = False status = TelescopeStatus.ABORTED break self._alt += alt_steps self._az += az_steps self._setRaDecFromAltAz() time.sleep(0.5) t += 0.5 self._slewing = False self.slewComplete(self.getPositionRaDec(), status)
def slewToAltAz(self, position): if not isinstance(position, Position): position = Position.fromAltAz(*position) self.slewBegin(self._getSite().altAzToRaDec(position)) alt_steps = position.alt - self.getAlt() alt_steps = float(alt_steps / 10.0) az_steps = position.az - self.getAz() az_steps = float(az_steps / 10.0) self._slewing = True self._abort.clear() status = TelescopeStatus.OK t = 0 while t < 5: if self._abort.isSet(): self._slewing = False status = TelescopeStatus.ABORTED break self._alt += alt_steps self._az += az_steps self._setRaDecFromAltAz() time.sleep(0.5) t += 0.5 self._slewing = False self.slewComplete(self.getPositionRaDec(), status)
def test_slew_abort(self): site = self.manager.getProxy("/Site/0") # go to know position self.tel.slewToRaDec(Position.fromRaDec(site.LST(), site["latitude"])) last = self.tel.getPositionRaDec() # clear event checkings FiredEvents = {} # drift it dest = Position.fromRaDec(last.ra + Coord.fromH(1), last.dec + Coord.fromD(10)) real_dest = None @callback(self.manager) def slewBeginClbk(target): global real_dest real_dest = target @callback(self.manager) def slewCompleteClbk(position, status): assert last.ra < position.ra < real_dest.ra assert last.dec < position.dec < real_dest.dec self.tel.slewBegin += slewBeginClbk self.tel.slewComplete += slewCompleteClbk # async slew def slew(): tel = self.manager.getProxy(self.TELESCOPE) tel.slewToRaDec(dest) pool = ThreadPool() pool.queueTask(slew) # wait thread to be scheduled time.sleep(2) # abort and test self.tel.abortSlew() pool.joinAll() # event checkings self.assertEvents(TelescopeStatus.ABORTED)
def test_changeEpoch(self): sirius_j2000 = Position.fromRaDec("06 45 08.9173", "-16 42 58.017") sirius_now = sirius_j2000.toEpoch(epoch=Epoch.NOW) print print sirius_j2000 print sirius_now
def getTargetAltAz(self): drv = self.getDriver() ret = drv.getTargetAltAz() if not isinstance(ret, Position): ret = Position.fromAltAz(*ret) return ret
def test_changeEpoch(self): sirius_j2000 = Position.fromRaDec("06 45 08.9173", "-16 42 58.017") sirius_now = sirius_j2000.toEpoch(epoch=Epoch.NOW) print() print(sirius_j2000) print(sirius_now)
def test_slew_abort (self): site = self.manager.getProxy("/Site/0") # go to know position self.tel.slewToRaDec(Position.fromRaDec(site.LST(), site["latitude"])) last = self.tel.getPositionRaDec() # clear event checkings FiredEvents = {} # drift it dest = Position.fromRaDec(last.ra+Coord.fromH(1), last.dec+Coord.fromD(10)) real_dest = None @callback(self.manager) def slewBeginClbk(target): global real_dest real_dest = target @callback(self.manager) def slewCompleteClbk(position, status): assert last.ra < position.ra < real_dest.ra assert last.dec < position.dec < real_dest.dec self.tel.slewBegin += slewBeginClbk self.tel.slewComplete += slewCompleteClbk # async slew def slew(): tel = self.manager.getProxy(self.TELESCOPE) tel.slewToRaDec(dest) pool = ThreadPool() pool.queueTask(slew) # wait thread to be scheduled time.sleep(2) # abort and test self.tel.abortSlew() pool.joinAll() # event checkings self.assertEvents(TelescopeStatus.ABORTED)
def slewToAltAz(self, position): site = self._getSite() if self.slewToRaDec( Position.altAzToRaDec(position, site['latitude'], site.LST()).toEpoch(Epoch.NOW)): self.stopTracking() return True return False
def test_precession(self): sirius_j2000 = Position.fromRaDec("06 45 08.9173", "-16 42 58.017") sirius_now = sirius_j2000.precess() print print sirius_j2000 print sirius_now
def slewToRaDec(self, position): # FIXME: validate limits? if not isinstance(position, Position): position = Position.fromRaDec(*position) drv = self.getDriver() drv.slewToRaDec(position)
def getTargetRaDec(self): drv = self.getDriver() ret = drv.getTargetRaDec() if not isinstance(ret, Position): ret = Position.fromRaDec(*ret) return ret
def _validateRaDec(self, position): site = self.getManager().getProxy("/Site/0") lst = site.LST() latitude = site["latitude"] altAz = Position.raDecToAltAz(position, latitude, lst) return self._validateAltAz(altAz)
class TelescopePark(Telescope): """Telescope with park/unpark support. """ __config__ = {"default_park_position": Position.fromAltAz(90, 180)} def park(self): """Park the telescope on the actual saved park position (L{setParkPosition}) or on the default position if none setted. When parked, the telescope will not track objects and may be turned off (if the scope was able to). @return: Nothing. @rtype: None """ def unpark(self): """Wake up the telescope of the last park operation. @return: Nothing. @rtype: None """ def isParked(self): """Ask if the telescope is at park position. @return: True if the telescope is parked, False otherwise. @rtype: bool """ def setParkPosition(self, position): """Defines where the scope will park when asked to. @param position: local coordinates to park the scope @type position: L{Position} @return: Nothing. @rtype: None """ def getParkPosition(self): """Get the Current park position. @return: Current park position. @rtype: L{Position} """ @event def parkComplete(self): """Indicates that the scope has parked successfuly. """ @event def unparkComplete(self): """Indicates that the scope has unparked (waked up)
def checkPointing(self): """ This method *chooses* a field to verify the telescope pointing. Then it does the pointing and verifies it. If unsuccesfull e-mail the operator for help isto em portugues eh chamado calagem Choice is based on some catalog (Landolt here) We choose the field closest to zenith """ # find where the zenith is site = self.getManager().getProxy("/Site/0") lst = site.LST() lat = site["latitude"] coords = Position.fromRaDec(lst, lat) self.log.info( "Check pointing - Zenith coordinates: %f %f" % (lst, lat)) tel = self.getTel() # use the Vizier catalogs to see what Landolt field is closest to # zenith self.log.debug("Calling landolt") fld = Landolt() fld.useTarget(coords, radius=45) obj = fld.find(limit=self["max_fields"]) print "Objects returned from Landolt", obj # get ra, dec to call pointVerify ra = obj[self.currentField]["RA"] dec = obj[self.currentField]["DEC"] name = obj[self.currentField]["ID"] print "Current object ", ra, dec, name self.log.info("Chose %s %f %f" % (name, ra, dec)) tel.slewToRaDec(Position.fromRaDec(ra, dec)) try: self.pointVerify() except Exception, e: printException(e) raise CantSetScopeException( "Can't set scope on field %s %f %f we are in trouble, call for help" % (name, ra, dec))
def _moveScope(self): """ Moves the scope, usually to zenith """ tel = self._getTel() try: self.log.debug("Skyflat Slewing scope to zenith") tel.slewToAltAz(Position.fromAltAz(90, 270)) except: self.log.debug("Error moving the telescope")
def __init__(self, buffer): # discard time buffer.recv(8) self.ra = struct.unpack("<1I", buffer.recv(4))[0] self.ra *= (math.pi / 0x80000000) self.ra = Coord.fromR(self.ra).toHMS() self.dec = struct.unpack("<1i", buffer.recv(4))[0] self.dec *= (math.pi / 0x80000000) self.dec = Coord.fromR(self.dec).toDMS() self.position = Position.fromRaDec(self.ra, self.dec)
def checkPointing(self): """ This method *chooses* a field to verify the telescope pointing. Then it does the pointing and verifies it. If unsuccesfull e-mail the operator for help isto em portugues eh chamado calagem Choice is based on some catalog (Landolt here) We choose the field closest to zenith """ # find where the zenith is site = self.getManager().getProxy("/Site/0") lst = site.LST() lat = site["latitude"] coords = Position.fromRaDec(lst, lat) self.log.info("Check pointing - Zenith coordinates: %f %f" % (lst, lat)) tel = self.getTel() # use the Vizier catalogs to see what Landolt field is closest to zenith self.log.debug("Calling landolt") fld = Landolt() fld.useTarget(coords, radius=45) obj = fld.find(limit=self["max_fields"]) print "Objects returned from Landolt", obj # get ra, dec to call pointVerify ra = obj[self.currentField]["RA"] dec = obj[self.currentField]["DEC"] name = obj[self.currentField]["ID"] print "Current object ", ra, dec, name self.log.info("Chose %s %f %f" % (name, ra, dec)) tel.slewToRaDec(Position.fromRaDec(ra, dec)) try: self.pointVerify() except Exception, e: printException(e) raise CantSetScopeException( "Can't set scope on field %s %f %f we are in trouble, call for help" % (name, ra, dec))
def __main__(self): tel = self.getManager().getProxy("/Telescope/0") cam = self.getManager().getProxy("/Camera/0") dome = self.getManager().getProxy("/Dome/0") autofocus = self.getManager().getProxy("/Autofocus/0") verify = self.getManager().getProxy("/PointVerify/0") landolt = Landolt() landolt.useTarget(Position.fromRaDec("00:38:00", "-22:00:00"), radius=45) landolt.constrainColumns({"Vmag": "<11"}) landolts = landolt.find(limit=3) for landolt in landolts: pos = Position.fromRaDec(landolt["RA"], landolt["DEC"]) self.log.info("Slewing to %s" % pos) tel.slewToRaDec(pos) while (tel.isSlewing() or not dome.isSyncWithTel()): self.log.info("Waiting dome...") self.log.info("Doing autofocus on %s" % pos) fit = autofocus.focus(target=Target.CURRENT, mode=Mode.FIT, exptime=20, start=0, end=7000, step=1000) self.log.info("Verifyng pointing...") verify.pointVerify() cam.expose(exp_time=120, shutter="OPEN", frames=1, filename="extincao-%s" % landolt["ID"].replace(" ", "_"))
def slewToAltAz(self, position): # FIXME: validate limits? if not isinstance(position, Position): position = Position.fromAltAz(*position) drv = self.getDriver() try: drv.slewToAltAz(position) except Exception, e: self.log.exception("Apollo 13 is out of control!")
def moveSouth(self, offset, rate=SlewRate.MAX): self._slewing = True pos = self.getPositionRaDec() pos = Position.fromRaDec(pos.ra, pos.dec + Coord.fromAS(-offset)) self.slewBegin(pos) self._dec += Coord.fromAS(-offset) self._setAltAzFromRaDec() self._slewing = False self.slewComplete(self.getPositionRaDec(), TelescopeStatus.OK)
def test_find(self): landolt = Landolt() landolt.useTarget(Position.fromRaDec("14:00:00", "-22:00:00"), radius=45) landolt.constrainColumns({"Vmag": "<10"}) data = landolt.find(limit=5) for obj in data: for k, v in obj.items(): print k, v
def chimera_handler(self, payload, root): t0 = time.time() # Check if it is a real GRB ra, dec = float( root.find( "./WhereWhen/ObsDataLocation/ObservationLocation/AstroCoords/Position2D/Value2/C1" ).text ), float( root.find( "./WhereWhen/ObsDataLocation/ObservationLocation/AstroCoords/Position2D/Value2/C2" ).text) packet_type = int( root.find("./What/Param[@name='Packet_Type']").attrib['value']) site = self.getSite() ephem_site = site.getEphemSite(site.ut()) grb = ephem.FixedBody() grb._ra, grb._dec = ra, dec grb.compute(ephem_site) # Conditions to pull the observation trigger # TODO: implement min_moon_distance -> Position(coord.fromD(grb.alt), coord.fromD(grb.az)) - site.moonpos() # In[8]: a = Position.fromAltAz(Coord.fromD(10), Coord.fromD(10)) # # In[9]: b = Position.fromAltAz(Coord.fromD(10), Coord.fromD(20)) # # In[11]: a.angsep(b).D # Out[11]: 10.0 moondist = Position.fromAltAz(Coord.fromD(float(grb.alt)), Coord.fromD(float(grb.az))).angsep( site.moonpos()) if moondist > self['obs-min_moondist']: self.log.debug("Moon is OK! Moon distance = %.2f deg" % moondist) else: self.log.debug("Moon is NOT OK! Moon distance = %.2f deg" % moondist) # TODO: check if Test_Notice != True (for INTEGRAL) if grb.alt >= self['obs-min_alt'] and packet_type in range( 1000): # self['obs-packets']: gal_coord = ephem.Galactic(grb) ebv = get_SFD_dust([gal_coord.long], [gal_coord.lat], dustmap=self.dust_file, interpolate=False) if ebv < self['obs-ebv_max']: self.log.debug('Total analysis time: %6.3f secs' % (time.time() - t0)) self.trigger_observation(ra, dec) else: self.log.debug( "Reject alert type %i. ALT = %.2f, RA = %.2f DEC = %.2f. Config: %d, %s" % (packet_type, grb.alt, ra, dec, self['obs-min_alt'], str(self['obs-packets'])))
def test_find (self): x = VizQuery() x.useCat("II/183A/") x.useColumns("*POS_EQ_RA_MAIN,*POS_EQ_DEC_MAIN,*ID_MAIN,Vmag,_r", sortBy="*POS_EQ_RA_MAIN") x.useTarget(Position.fromRaDec("14:00:00","-22:00:00"),radius=45) data = x.find(limit=5) for obj in data: for k,v in obj.items(): print k, v print
def test_find (self): landolt = Landolt() landolt.useTarget(Position.fromRaDec("14:00:00","-22:00:00"),radius=45) landolt.constrainColumns({"Vmag":"<10"}) data = landolt.find(limit=5) for obj in data: for k,v in obj.items(): assert k assert v print k, v
def test_slew_to_ra_dec (self): m = self.m print self.printCoord (header=True) ra = m.getRa() m.slewToRaDec (Position.fromRaDec(ra, "-70:00:00")) #m.slewToRaDec (Position.fromRaDec("13h25m38.903s", "-11:12:24.928")) self.printCoord()
def test_find(self): x = VizQuery() x.useCat("II/183A/") x.useColumns("*POS_EQ_RA_MAIN,*POS_EQ_DEC_MAIN,*ID_MAIN,Vmag,_r", sortBy="*POS_EQ_RA_MAIN") x.useTarget(Position.fromRaDec("14:00:00", "-22:00:00"), radius=45) data = x.find(limit=5) for obj in data: for k, v in list(obj.items()): print(k, v) print()
def _parseSesame(xml): try: sesame = ET.fromstring(xml.replace("&", "&")) target = sesame.findall("Target") if target: for resolver in target[0].findall("Resolver"): jpos = resolver.find("jpos") if jpos is None: continue return Position.fromRaDec(*jpos.text.split()) except ExpatError, e: return False
def _parseSesame (xml): try: sesame = ET.fromstring(xml.replace("&", "&")) target = sesame.findall("Target") if target: for resolver in target[0].findall("Resolver"): jpos = resolver.find("jpos") if jpos is None: continue return Position.fromRaDec(*jpos.text.split()) except ExpatError, e: return False
def slewToRaDec(self, position): if not isinstance(position, Position): position = Position.fromRaDec(position[0], position[1], epoch=Epoch.J2000) self._validateRaDec(position) self.slewBegin(position) # Change position epoch to J2000. # Most of the Telescopes must have this precession calculation, otherwise pointing to positions of epochs # different of J2000 will point the telescope to a wrong position. # This should be done after self.slewBegin() if position.epoch != Epoch.J2000: position = position.toEpoch(Epoch.J2000) ra_steps = position.ra - self.getRa() ra_steps = float(ra_steps / 10.0) dec_steps = position.dec - self.getDec() dec_steps = float(dec_steps / 10.0) self._slewing = True self._abort.clear() status = TelescopeStatus.OK t = 0 while t < 5: if self._abort.isSet(): self._slewing = False status = TelescopeStatus.ABORTED break self._ra += ra_steps self._dec += dec_steps self._setAltAzFromRaDec() time.sleep(0.5) t += 0.5 self._slewing = False self.startTracking() self.slewComplete(self.getPositionRaDec(), status)
def test_park(self): # FIXME: make a real test. raise SkipTest() def printPosition(): print self.tel.getPositionRaDec(), self.tel.getPositionAltAz() sys.stdout.flush() print ra = self.tel.getRa() dec = self.tel.getDec() print "current position:", self.tel.getPositionRaDec() print "moving to:", (ra - "01 00 00"), (dec - "01 00 00") self.tel.slewToRaDec( Position.fromRaDec(ra - Coord.fromH(1), dec - Coord.fromD(1))) for i in range(10): printPosition() time.sleep(0.5) print "parking..." sys.stdout.flush() self.tel.park() t0 = time.time() wait = 30 for i in range(10): printPosition() time.sleep(0.5) while time.time() < t0 + wait: print "\rwaiting ... ", sys.stdout.flush() time.sleep(1) print "unparking..." sys.stdout.flush() self.tel.unpark() for i in range(10): printPosition() time.sleep(0.5)
def __str__(self): raDec = Position.fromRaDec(self.targetRa, self.targetDec, 'J2000') if self.observed: msg = "#[id: %5d] [name: %15s %s (ah: %.2f)] [type: %s] #LastObverved@: %s" return msg % (self.id, self.name, raDec, self.targetAH, self.type, self.lastObservation) else: msg = "#[id: %5d] [name: %15s %s (ah: %.2f)] [type: %s] #NeverObserved" return msg % ( self.id, self.name, raDec, self.targetAH, self.type, )
def test_park (self): # FIXME: make a real test. raise SkipTest() def printPosition(): print self.tel.getPositionRaDec(), self.tel.getPositionAltAz() sys.stdout.flush() print ra = self.tel.getRa() dec = self.tel.getDec() print "current position:", self.tel.getPositionRaDec() print "moving to:", (ra-"01 00 00"), (dec-"01 00 00") self.tel.slewToRaDec(Position.fromRaDec(ra-Coord.fromH(1), dec-Coord.fromD(1))) for i in range(10): printPosition() time.sleep(0.5) print "parking..." sys.stdout.flush() self.tel.park() t0 = time.time() wait = 30 for i in range(10): printPosition() time.sleep(0.5) while time.time() < t0+wait: print "\rwaiting ... ", sys.stdout.flush() time.sleep(1) print "unparking..." sys.stdout.flush() self.tel.unpark() for i in range(10): printPosition() time.sleep(0.5)
def __main__(self): tel = self._getTel() tel.slewComplete += self.getProxy()._updateSlewPosition tel.abortComplete += self.getProxy()._updateSlewPosition self._updateSlewPosition(tel.getPositionRaDec()) # From man(7) fifo: The FIFO must be opened on both ends #(reading and writing) before data can be passed. Normally, #opening the FIFO blocks until the other end is opened also # force non-blocking open fd = os.open(self._in_fifo, os.O_RDONLY | os.O_NONBLOCK) in_fifo = os.fdopen(fd, "r") while not self._loop_abort.isSet(): ret = select([in_fifo], [], [], 0) # timeout if not any(ret): time.sleep(1) continue try: edb = in_fifo.readline() # writer not connected (XEphem closed) if not edb: time.sleep(1) continue edb = edb.split(",") ra = edb[2].split("|")[0].strip() dec = edb[3].split("|")[0].strip() target = Position.fromRaDec(ra, dec) self.log.info("XEphem FIFO changed: slewing to %s" % target) self._getTel().slewToRaDec(target) except (ValueError, IndexError): self.log.exception("Cannot convert XEphem EDB to Position.") continue except: self.log.exception("Something wrong...")
def _watchTrackingStopped(self, position, status): self.setFlag("telescope",InstrumentOperationFlag.READY) self.broadCast('Telescope tracking stopped with status %s.' % status) if status == TelescopeStatus.OBJECT_TOO_LOW: # Todo: Make this an action on the checklist database, so user can configure what to do robobs = self.getRobObs() sched = self.getSched() robobs.stop() sched.stop() tel = self.getTel() from chimera.util.position import Position from chimera.util.coord import Coord park_position = Position.fromAltAz(Coord.fromD(80),Coord.fromD(89)) tel.slewToAltAz(park_position) robobs.reset_scheduler() robobs.start() robobs.wake()
def __main__(self): tel = self._getTel() tel.slewComplete += self.getProxy()._updateSlewPosition self._updateSlewPosition(tel.getPositionRaDec(), None) # From man(7) fifo: The FIFO must be opened on both ends #(reading and writing) before data can be passed. Normally, # opening the FIFO blocks until the other end is opened also # force non-blocking open fd = os.open(self._in_fifo, os.O_RDONLY | os.O_NONBLOCK) in_fifo = os.fdopen(fd, "r") while not self._loop_abort.isSet(): ret = select([in_fifo], [], [], 0) # timeout if not any(ret): time.sleep(1) continue try: edb = in_fifo.readline() # writer not connected (XEphem closed) if not edb: time.sleep(1) continue edb = edb.split(",") ra = edb[2].split("|")[0].strip() dec = edb[3].split("|")[0].strip() target = Position.fromRaDec(ra, dec) self.log.info("XEphem FIFO changed: slewing to %s" % target) self._getTel().slewToRaDec(target) except (ValueError, IndexError): self.log.exception("Cannot convert XEphem EDB to Position.") continue except: self.log.exception("Something wrong...")
def slewToRaDec(self, position): if not isinstance(position, Position): position = Position.fromRaDec(position[0], position[1], epoch=Epoch.J2000) self._validateRaDec(position) self.slewBegin(position) ra_steps = position.ra - self.getRa() ra_steps = float(ra_steps / 10.0) dec_steps = position.dec - self.getDec() dec_steps = float(dec_steps / 10.0) self._slewing = True self._epoch = position.epoch self._abort.clear() status = TelescopeStatus.OK t = 0 while t < 5: if self._abort.isSet(): self._slewing = False status = TelescopeStatus.ABORTED break self._ra += ra_steps self._dec += dec_steps self._setAltAzFromRaDec() time.sleep(0.5) t += 0.5 self._slewing = False self.startTracking() self.slewComplete(self.getPositionRaDec(), status)
def test_stress_dome_track (self): dome = self.manager.getProxy(self.DOME) tel = self.manager.getProxy(self.TELESCOPE) dome.track() for i in range(10): FiredEvents = {} self.setupEvents() ra = "%d %d 00" % (random.randint(7,15), random.randint(0,59)) dec = "%d %d 00" % (random.randint(-90,0), random.randint(0,59)) tel.slewToRaDec(Position.fromRaDec(ra, dec)) dome.syncWithTel() assertDomeAz(dome.getAz(), tel.getAz(), dome["az_resolution"]) self.assertEvents(sync=True) time.sleep(random.randint(0,10))
def test_sync (self): # get current position, drift the scope, and sync on the first # position (like done when aligning the telescope). real = self.tel.getPositionRaDec() @callback(self.manager) def syncCompleteClbk(position): assert position.ra == real.ra assert position.dec == real.dec self.tel.syncComplete += syncCompleteClbk # drift to "real" object coordinate drift = Position.fromRaDec(real.ra+Coord.fromH(1), real.dec+Coord.fromD(1)) self.tel.slewToRaDec(drift) self.tel.syncRaDec(real) time.sleep(2)
def telegram_set_target(self, bot, update, args, job_queue, chat_data): if len(args) != 2: update.message.reply_text( "Usage: /set HH:MM:SS.S DD:MM:SS.S or /set ra dec (J2000)") else: self.last_update = datetime.datetime.now() ra = Coord.fromHMS(args[0]) if ":" in args[0] else Coord.fromD( float(args[0])) dec = Coord.fromDMS(args[1]) if ":" in args[1] else Coord.fromD( float(args[1])) self.target = Position.fromRaDec(ra, dec) site = self.getSite() lst = site.LST_inRads() alt = float(site.raDecToAltAz(self.target, lst).alt) # TODO: reject if alt< telescope_min_alt! moonPos = site.moonpos() moonRaDec = site.altAzToRaDec(moonPos, lst) moonDist = self.target.angsep(moonRaDec) update.message.reply_text( 'Hello {} arg is {} {}. Object alt = {}, Moon dist = {}'. format(update.message.from_user.first_name, args[0], args[1], alt, moonDist))
def _moveScope(self, pierSide=None): """ Moves the scope, usually to zenith """ tel = self._getTel() if pierSide is not None and tel.features(TelescopePier): self.log.debug("Setting telescope pier side to %s." % tel.getPierSide().__str__().lower()) tel.setSideOfPier(self['pier_side']) else: self.log.warning("Telescope does not support pier side.") try: self.log.debug("Slewing scope to alt {} az {}".format(self["flat_alt"], self["flat_az"])) tel.slewToAltAz(Position.fromAltAz(Coord.fromD(self["flat_alt"]), Coord.fromD(self["flat_az"]))) if tel.isTracking(): tel.stopTracking() except: self.log.debug("Error moving the telescope")
def pointVerify (self): """ Checks telescope pointing Checks the pointing. If abs ( telescope coordinates - image coordinates ) > tolerance move the scope take a new image test again do this while ntrials < max_trials Returns True if centering was succesful False if not """ # take an image and read its coordinates off the header image = None try: image = self._takeImage() print "image name %s", image.filename() except: self.log.error( "Can't take image" ) raise ra_img_center = image["CRVAL1"] # expects to see this in image dec_img_center= image["CRVAL2"] currentImageCenter = Position.fromRaDec(Coord.fromD(ra_img_center), Coord.fromD(dec_img_center)) tel = self.getTel() # analyze the previous image using # AstrometryNet defined in util try: wcs_name = AstrometryNet.solveField(image.filename(),findstarmethod="sex") except NoSolutionAstrometryNetException, e: raise e
def test_slew (self): site = self.manager.getProxy("/Site/0") dest = Position.fromRaDec(site.LST(), site["latitude"]) real_dest = None @callback(self.manager) def slewBeginClbk(target): global real_dest real_dest = target @callback(self.manager) def slewCompleteClbk(position, status): assertEpsEqual(position.ra, real_dest.ra, 60) assertEpsEqual(position.dec, real_dest.dec, 60) self.tel.slewBegin += slewBeginClbk self.tel.slewComplete += slewCompleteClbk self.tel.slewToRaDec(dest) # event checkings self.assertEvents(TelescopeStatus.OK)
def park (self): if self.isParked (): return True # 1. slew to park position FIXME: allow different park # positions and conversions from ra/dec -> az/alt site = self.getManager().getProxy("/Site/0") self.slewToRaDec(Position.fromRaDec(str(self.getLocalSiderealTime()), site["latitude"])) # 2. stop tracking self.stopTracking () # 3. power off #self.powerOff () self._parked = True self.parkComplete() return True
def slewToAz(self, az): # Astelco Dome will only enable slew if it is not tracking # If told to slew I will check if the dome is syncronized with # with the telescope. If it is not it¡ will wait until it gets # in sync or timeout... if self.getMode() == Mode.Track: raise AstelcoDomeException('Dome is in track mode... Slew is completely controled by AsTelOS...') # self.log.warning('Dome is in track mode... Slew is completely controled by AsTelOS...') # self.slewBegin(az) # # start_time = time.time() # self._abort.clear() # self._slewing = True # caz = self.getAz() # # while self.isSlewing(): # # time.sleep(1.0) # if time.time() > (start_time + self._maxSlewTime): # self.log.warning('Dome syncronization timed-out...') # self.slewComplete(self.getAz(), DomeStatus.TIMEOUT) # return 0 # elif self._abort.isSet(): # self._slewing = False # self.slewComplete(self.getAz(), DomeStatus.ABORTED) # return 0 # elif abs(caz - self.getAz()) < 1e-6: # self._slewing = False # self.slewComplete(self.getAz(), DomeStatus.OK) # return 0 # else: # caz = self.getAz() # # self.slewComplete(self.getAz(), DomeStatus.OK) else: self.log.info('Slewing to %f...' % az) start_time = time.time() self._abort.clear() self._slewing = True current_az = self.getAz() tpl = self.getTPL() self.slewBegin(az) cmdid = tpl.set('POSITION.INSTRUMENTAL.DOME[0].TARGETPOS', '%f' % az) reference_alt = Coord.fromD(0.) desired_position = Position.fromAltAz(reference_alt, az) # Wait for command to be completed cmd = tpl.getCmd(cmdid) while not cmd.complete: if time.time() > (start_time + self._maxSlewTime): self.log.warning('Dome syncronization timed-out...') self.slewComplete(self.getAz(), DomeStatus.ABORTED) return 0 cmd = tpl.getCmd(cmdid) # time.sleep(self['stabilization_time']) # Wait dome arrive on desired position while True: current_position = Position.fromAltAz(reference_alt, current_az) if time.time() > (start_time + self._maxSlewTime): self.slewComplete(self.getAz(), DomeStatus.ABORTED) raise AstelcoDomeException('Dome syncronization timed-out...') elif self._abort.isSet(): self._slewing = False tpl.set('POSITION.INSTRUMENTAL.DOME[0].TARGETPOS', current_az) self.slewComplete(self.getAz(), DomeStatus.ABORTED) return 0 elif abs(current_position.angsep(desired_position)) < tpl.getobject( 'POINTING.SETUP.DOME.MAX_DEVIATION') * 2.0: self._slewing = False self.slewComplete(self.getAz(), DomeStatus.OK) return 0 else: current_az = self.getAz() self.slewComplete(self.getAz(), DomeStatus.OK)
def getPositionAltAz(self): self._telescope.GetAzAlt() return Position.fromAltAz(Coord.fromD(self._telescope.dAlt), Coord.fromD(self._telescope.dAz))