def get_passes(self): passes_dict = [] # use time of 4PM today for all calculations so that it always gets next rise and set times for this evening mytz = pytz.timezone(self.tz) eptz = pytz.timezone('utc') now = datetime.date.today() afternoon = mytz.localize( datetime.datetime(now.year,now.month,now.day)+ datetime.timedelta(hours=16)) eptafternoon = afternoon.astimezone(eptz) # print "eptafternoon", eptafternoon # setup current location here = ephem.Observer() here.lon = str(self.lon) here.lat = str(self.lat) here.elev = self.alt here.date = eptafternoon # print here # do lookup from NASA website: url = params.nasa_url req = urllib2.Request(url) response = urllib2.urlopen(req) data = response.read() # look for TWO LINE MEAN ELEMENT SET in file table = data.split("TWO LINE MEAN ELEMENT SET")[1] line1 = table.splitlines()[3] line2 = table.splitlines()[4] # print "line 1:", line1 # print "line 2:", line2 iss = ephem.readtle('ISS', \ line1, \ line2) # get next 5 passes, there would never be more than 5 passes after 4PM for apass in range(0,5): iss.compute(here) iss_np = here.next_pass(iss) iss_r = ephem.localtime(iss_np[0]) iss_s = ephem.localtime(iss_np[4]) # print "pass n: iss rise, set:", apass, iss_r, iss_s # Store the data in a list passes_dict.append({"begin_time": iss_r, "end_time": iss_s}) here.date = iss_np[4] # Return all the data return passes_dict
def get_satellites(self): # GLONASS='http://celestrak.com/NORAD/elements/glo-ops.txt' SBAS = "http://celestrak.com/NORAD/elements/sbas.txt" GPSO = "http://www.celestrak.com/NORAD/elements/gps-ops.txt" # rospy.loginfo("[GPS] Get Glonass Sat. data") # r = urlopen(GLONASS).read() # data = r.split('\r\n') # sat_glonass = [] # for tle in chunks(data, 3): # if len(tle)==3: # sat_glonass.append(ephem.readtle(str(tle[0]), str(tle[1]), str(tle[2]))) rospy.loginfo("[GPS] Get SBAS Sat. data") r = urlopen(SBAS).read() data = r.split("\r\n") sat_sbas = [] for tle in chunks(data, 3): if len(tle) == 3: a = str(tle[0]) if a.find("EGNOS") > 0: sat_sbas.append(ephem.readtle(str(tle[0]), str(tle[1]), str(tle[2]))) rospy.loginfo("[GPS] Get GPS Operational Sat. data") r = urlopen(GPSO).read() data = r.split("\r\n") sat_gosop = [] for tle in chunks(data, 3): if len(tle) == 3: sat_gosop.append(ephem.readtle(str(tle[0]), str(tle[1]), str(tle[2]))) return sat_sbas, sat_gosop
def test_newlineTLE(self): """Make sure TLE strings with newlines are accepted.""" # based on bug report from Reto Schüttel, 2008 Dec 10 readtle('HST \n', '1 20580U 90037B 04296.45910607 .00000912 ' ' 00000-0 59688-4 0 1902\n', '2 20580 28.4694 17.3953 0004117 265.2946 ' '94.7172 14.99359833594524\n')
def check_tle_format(l0, l1, l2): """Static method Checks whether the format for a given TLE is correct or not. :param l0: Line#0 of the TLE file :param l1: Line#1 of the TLE file :param l2: Line#2 of the TLE file :return: True if the operation could succesuffly be completed """ l0, l1, l2 = OrbitalSimulator.normalize_string(l0, l1, l2) ephem.readtle(l0, l1, l2) return True
def test_gps(self): import ephem dnd = ephem.Observer() dnd.lon = str(location.Dunedin.lon.to_degrees()) dnd.lat = str(location.Dunedin.lat.to_degrees()) dnd.elevation = location.Dunedin.alt dnd.pressure = 0.0 t = utc.utc_datetime(2013,9,20,0,0,3) dnd.date = t for svnum in range(31,32): l1 = 'GPS BIIRM-2 (PRN 31) ' l2 = '1 29486U 06042A 13264.26023969 -.00000084 00000-0 00000+0 0 2292' l3 = '2 29486 56.1466 336.5502 0081195 316.5190 69.5394 2.00563866 51246' j = ephem.readtle(l1,l2,l3) # http://blog.thetelegraphic.com/2012/gps-sattelite-tracking-in-python-using-pyephem/ #j = ephem.Gps(svnum) j.compute(dnd) ra_e = angle.from_rad(j.ra.real) dec_e= angle.from_rad(j.dec.real) sv = GpsSatellite(svnum, location.Dunedin) ra, dec = sv.radec(t) print angle.wrap_360(ra.to_degrees()) self.assertAlmostEqual(ra.to_degrees(), ra_e.to_degrees(), 0) self.assertAlmostEqual(dec.to_degrees(), dec_e.to_degrees(), 0)
def tledata(name, line1, line2): # process TLE data tle_rec = ephem.readtle(name, line1, line2) latitude = [] longitude = [] altitude = [] right_asc = [] declination = [] speed = [] # define time date_utcnow = datetime.datetime.utcnow() # get the data into the table for t in range(90): # interval a second date_delta = datetime.timedelta(seconds=t) date_prediction = date_utcnow + date_delta # compute TLE data tle_rec.compute(date_prediction) latitude.append(tle_rec.sublat / ephem.degree) longitude.append(tle_rec.sublong / ephem.degree) altitude.append(tle_rec.elevation) right_asc.append(str((tle_rec.ra))) declination.append(str(ephem.hours(tle_rec.dec))) #speed.append(tle_rec.range_velocity) # return as dictionary (python) or object (JavaScript) return {'latitude': latitude, 'longitude': longitude, 'altitude': altitude, 'right_asc': right_asc, 'declination': declination,}
def get_location(tle, now=None, lat=None, lng=None): """Compute the current location of the ISS""" now = now or datetime.datetime.utcnow() lat = lat or 37.7701 lng = lng or -122.4664 satellite = ephem.readtle(str(tle[0]), str(tle[1]), str(tle[2])) # Compute for current location observer = ephem.Observer() observer.lat = lat observer.lon = lng observer.elevation = 0 observer.date = now satellite.compute(observer) lon = degrees(satellite.sublong) lat = degrees(satellite.sublat) # Return the relevant timestamp and data data = {'position': {'latitude': lat, 'longitude': lon}, 'visible': float(repr(satellite.alt)) > 0 and float(repr(satellite.alt)) < math.pi, 'altitude': satellite.alt, 'azimuth': satellite.az, 'range': satellite.range, 'velocity': satellite.range_velocity, 'name': satellite.name} return data
def set_satellite(full_name, nick_name=''): with open(TLE_FILE, 'r') as fname: lines = fname.read().split('\n') counter = 0 my_lines = list() for line in lines: if matches(full_name, line): my_lines.append(line) counter = 1 elif counter > 0 and counter < 3: my_lines.append(line) counter = counter + 1 elif counter == 3: break if len(my_lines) != 3: raise ValueError('Unable to find satellite') sat_name = full_name if nick_name == '' else nick_name # May throw an exception ret = ephem.readtle(sat_name, my_lines[1], my_lines[2]) save_current(full_name, nick_name) global sat sat = ret global grnd
def __getitem__(self, name): self.load(name) if self.entries: tle = self.entries[0] return ephem.readtle(name, *tle) else: raise KeyError('%s not found')
def add_satellite(self, tle1, tle2, tle3, friendly_name=None): """ Adds a satellite to the tracker. Args: tle1: line 1 of the TLE of the satellite. tle2: line 2 of the TLE of the satellite. tle3: line 3 of the TLE of the satellite. friendly_name: name to use for satellite within tracker. Returns: True if satellite added correctly. False if there was an error. If friendly_name is not given, line 1 of the TLE is used for it. """ try: sat_ephem = ephem.readtle(tle1, tle2, tle3) except ValueError: print(("error:", "ephem object", "tle values", sys.exc_info()[0])) return False except: print(("error:", "ephem object", sys.exc_info()[0])) return False if friendly_name is None: friendly_name = tle1 self.satellites['friendly_name'] = sat_ephem return True
def setup_satellite(): """Get the Body for the target satellite ICO F2 from its TLE.""" ico_f2 = ephem.readtle( 'ICO F2', '1 26857U 01026A 16172.60175106 -.00000043 00000-0 00000+0 0 9997', '2 26857 044.9783 5.1953 0013193 227.2968 127.4685 03.92441898218058') return ico_f2
def add_satellite_from_tle(self, tle_dict, friendly_name=None): """ Adds a satellite to the tracker using a dictionary containing the TLE info. Args: tle_dict: line 1 of the TLE of the satellite. friendly_name: name to use for satellite within tracker. Returns: True if satellite added correctly. False if there was an error. If friendly_name is not given, line 1 of the TLE is used for it. """ if 'TLE_LINE0' in tle_dict and 'TLE_LINE1' in tle_dict and 'TLE_LINE2' in tle_dict: tle1 = tle_dict['TLE_LINE0'] tle2 = tle_dict['TLE_LINE1'] tle3 = tle_dict['TLE_LINE2'] else: return False try: sat_ephem = ephem.readtle(tle1, tle2, tle3) except ValueError: print(("error:", "ephem object", "tle values", sys.exc_info()[0])) return False except: print(("error:", "ephem object", sys.exc_info()[0])) return False if friendly_name is None: friendly_name = tle1 self.satellites[friendly_name] = sat_ephem return True
def get_times(tle, elevation, location): sat = ephem.readtle(str(tle[0]), str(tle[1]), str(tle[2])) horizon = '-0:34' viewer = ephem.Observer() viewer.lon, viewer.lat = location.longitude, location.latitude now = datetime.utcnow() viewer.date = now viewer.horizon=horizon i = 0 times = [] #get 50 times to view satellite while i < 50: sat.compute(viewer) np = viewer.next_pass(sat) next_pass_times = np[::2] if None in next_pass_times: break sun = ephem.Sun() sun.compute(viewer) sun_alt = math.degrees(sun.alt) if sat.eclipsed is False: times.append(next_pass_times[0].datetime().strftime("%Y-%m-%dT%H:%M:%S")) i = i + 1 viewer.date = next_pass_times[-1] return times
def __init__(self, tle_name, tle_url, frequency, output_prefix): self.tle_name = tle_name self.output_prefix = output_prefix self.frequency = frequency self.next_check_time = ephem.now() # download TLE list tle_fd = urllib2.urlopen(self.tle_url_base + tle_url) tle_list = [] for line, i in zip(tle_fd, itertools.cycle(xrange(3))): if i == 0: tle_list.append([]) tle_list[-1].append(line.strip()) # scan TLEs for this satellite self.tle = None for tle in tle_list: if tle[0] == tle_name: self.tle = tle[1:] break if self.tle is None: raise RuntimeError('TLE "%s" not found' % tle_name) # init ephem body object self.body = ephem.readtle(tle_name, self.tle[0], self.tle[1])
def get_footprints_kml(): footprint_placemarks = '' color = _config.get('tracking','footprint_color') for kep in _keps.values(): kep_ephem = ephem.readtle(kep[0], kep[1], kep[2]) kep_ephem.compute(ephem.now()) lon = kep_ephem.sublong lat = kep_ephem.sublat elevation = kep_ephem.elevation coords = '' for point in get_footprint_points(lat, lon, elevation): coords += '%lf,%lf\n' % (point[0], point[1]) tokens = { '[NAME]':kep[0], '[DESCRIPTION]':'%s' % (kep[0]), '[COLOR]':color, '[COORDS]': coords } footprint_placemarks += swap(_satellite_footprint_polygon_template, tokens) tokens = { '[PLACEMARKS]':footprint_placemarks, } return swap(_satellite_footprint_template_main, tokens)
def load_o3bsats(): ''' Read the list of ob3 satellites from the Celestrak site and create a list of RadioGeosat objects containing all satellites. ''' # Retrieve TLE file for o3b satellites from Celestrak site. f = urllib2.urlopen('http://www.celestrak.com/NORAD/elements/other-comm.txt') lines = f.readlines() f.close() nlines = len(lines) # use every 3 lines to create another RadioGeosat object satlist = [] for i in range(0,nlines,3): if lines[i+2][9:16] == ' 0.0000': # aa.compute() hangs for a satellite with zero inclination! # Change to 0.0001 degrees, and do not forget to change the checksum. chksum = str(int(lines[i+2][-4:]) + 1) lines[i+2] = lines[i+2][:9]+' 0.0001'+lines[i+2][16:-4]+chksum try: geosat_body = ephem.readtle(lines[i], lines[i+1], lines[i+2]) src = RadioGeosat(geosat_body) # convert from an ephem Body object to a RadioGeosat object satlist.append(src) except: print 'Error in ephem.readtle: o3bsat', lines[i].strip(), 'not added to source catalog.' return satlist
def __get_iss_data(self): r = requests.get("http://celestrak.com/NORAD/elements/stations.txt") tle_data = r.text logger.info("Requested celestrak data. Cached: {0}".format(r.from_cache)) iss_tle = [str(l).strip() for l in tle_data.split('\r\n')[:3]] return ephem.readtle(*iss_tle)
def get_sat_tracks_from_tle(datestr): """ Program to build the satellite tracks from the two line element file """ import ephem import numpy as np from map_interactive import get_tle_from_file try: sat = get_tle_from_file('.\sat.tle') except: try: from gui import gui_file_select_fx fname = gui_file_select_fx(ext='*.tle',ftype=[('All files','*.*'),('Two Line element','*.tle')]) sat = get_tle_from_file(fname) except: import tkMessageBox tkMessageBox.showerror('No sat','There was an error reading the sat.tle file') return None for k in sat.keys(): sat[k]['ephem'] = ephem.readtle(k,sat[k]['tle1'],sat[k]['tle2']) sat[k]['d'] = [ephem.Date(datestr+' 00:00')] sat[k]['ephem'].compute(sat[k]['d'][0]) sat[k]['lat'] = [np.rad2deg(sat[k]['ephem'].sublat)] sat[k]['lon'] = [np.rad2deg(sat[k]['ephem'].sublong)] for t in xrange(24*60*2): d = ephem.Date(sat[k]['d'][t]+ephem.minute/2.0) sat[k]['d'].append(d) sat[k]['ephem'].compute(d) sat[k]['lat'].append(np.rad2deg(sat[k]['ephem'].sublat)) sat[k]['lon'].append(np.rad2deg(sat[k]['ephem'].sublong)) return sat
def get_next_passes(self, lat, lon, altitude, count, force_visible=False): '''Returns a list of the next visible passes for the ISS''' tle_data = requests.get("http://celestrak.com/NORAD/elements/stations.txt").text # Do not scrape all the time for release! iss_tle = [str(l).strip() for l in tle_data.split('\r\n')[:3]] iss = ephem.readtle(*iss_tle) location = ephem.Observer() location.lat = str(lat) location.long = str(lon) location.elevation = altitude # Ignore effects of atmospheric refraction location.pressure = 0 location.horizon = '5:00' location.date = datetime.utcnow() passes = [] for p in xrange(count): tr, azr, tt, altt, ts, azs = location.next_pass(iss) duration = int((ts - tr) * 60 * 60 * 24) year, month, day, hour, minute, second = tr.tuple() dt = datetime(year, month, day, hour, minute, int(second)) location.date = tr iss.compute(location) if not (force_visible and iss.eclipsed): passes.append({"risetime": timegm(dt.timetuple()), "duration": duration}) location.date = tr + 25 * ephem.minute return {"response": passes }
def main(): begin_timestamp = float(sys.stdin.readline()) duration_seconds = float(sys.stdin.readline()) latitude_degrees = float(sys.stdin.readline()) longitude_degrees = float(sys.stdin.readline()) elevation_metres = float(sys.stdin.readline()) min_altitude_degrees = float(sys.stdin.readline()) min_azimuth_degrees = float(sys.stdin.readline()) max_azimuth_degrees = float(sys.stdin.readline()) tle = [sys.stdin.readline(), sys.stdin.readline(), sys.stdin.readline()] obs = ephem.Observer() obs.lat = math.radians(latitude_degrees) obs.lon = math.radians(longitude_degrees) obs.elevation = elevation_metres body = ephem.readtle(*tle) def is_visible(body): return IsVisible( body, math.radians(min_altitude_degrees), math.radians(min_azimuth_degrees), math.radians(max_azimuth_degrees), ) begin_time = ephem.Date(datetime.datetime.utcfromtimestamp(begin_timestamp)) passes = NextPasses(body, begin_time, duration_seconds, obs, is_visible) print len(passes) for p in passes: print p.Serialize()
def loadTLE(TLEFileName, verbose=False): """ Loads a TLE file and creates a list of satellites. Parameters: TLEFileName: name of TLE file Returns: listSats: List from satellites decoded from TLE """ f = open(TLEFileName) listSats = [] l1 = f.readline() while l1: l2 = f.readline() l3 = f.readline() # print("l1 = %s", l1) # print("l2 = %s", l2) # print("l3 = %s", l3) sat = ephem.readtle(l1, l2, l3) listSats.append(sat) if verbose: print(' decoded TLE for %s' % sat.name) l1 = f.readline() f.close() if verbose: print(" %i satellites loaded into list\n" % len(listSats)) return listSats
def get_iss_position(): now = datetime.utcnow() earth = ephem.Observer() earth.elevation = 80 # Meters earth.date = now tle_file = file('iss_tle.txt', 'r') iss_tle = tle_file.read().splitlines() tle_file.close() iss = ephem.readtle(*iss_tle) iss.compute(earth) response = json.dumps({ 'date': now.isoformat(), 'lat': degrees(iss.sublat), 'long': degrees(iss.sublong) }) content_type = 'application/json' callback = request.args.get('callback', '') if callback: content_type = 'application/javascript' response = '%s(%s);' % (callback, response) resp = Response(response, content_type=content_type) return resp
def getPosition(self, date): """ Return the J2000 position of the space object for the given date. Note that you can also use the call operator:: iss = EphemerisCalculator(path) iss(date) :type date: datetime.datetime :rtype: ndarray of xyz J2000 coordinates in km """ tlelines = self.getTLE(date) tle = ephem.readtle('foo', tlelines[0], tlelines[1]) date = ephem.Date(date) if tle._epoch > date: raise Exception("The epoch of the earliest available TLE is AFTER the requested date. " + "Are you missing historic TLE data?") if (date - tle._epoch > 24*ephem.hour): warnings.warn('closest TLE epoch is ' + str((date - tle._epoch)*24) + 'h away from photo time') tle.compute(date) # see http://stackoverflow.com/q/19426505/60982 earthRadiusPyEphem = 6378.16 * units.km distanceEarthCenter = tle.elevation*units.m + earthRadiusPyEphem xyz = coord.distances.spherical_to_cartesian(distanceEarthCenter.to(units.km).value, tle.a_dec, tle.a_ra) return np.array(xyz)
def loadTLE(): # download weather and amateur tle files from celestrak. For know it gets new # files every time it runs. then it copies both files to "sat.txt" touch(_workDir + 'special.tle') urllib.urlretrieve('http://www.celestrak.com/NORAD/elements/amateur.txt', _workDir + 'amateur.txt') urllib.urlretrieve('http://www.celestrak.com/NORAD/elements/weather.txt', _workDir + 'weather.txt') filenames = [_workDir + 'amateur.txt'] + [_workDir + 'weather.txt'] + [_workDir + 'special.tle'] with open('sat.txt', 'w') as fout: for line in fileinput.input(filenames): fout.write(line) f = open(_tleFile) z = [] line1 = f.readline() while line1: # read tle and create an object for each satellite line2 = f.readline() line3 = f.readline() # We are only interested in LEO (Low Earth Orbit) satellites so check the mean motion # of the satellite. If it is below 2.0 skip over that satellite. # See http://en.wikipedia.org/wiki/Two-line_element_set for an explanation of the # TKE file layout. if float(line3[52:62]) > 2.0: y = ephem.readtle(line1,line2,line3) z.append(y) print y.name line1 = f.readline() f.close() print "%i satellites loaded into list"%len(z) return z
def __init__(self): self.iss = ephem.readtle("ISS", "1 25544U 98067A 11317.43923700 .00025400 00000-0 30934-3 0 4247" , "2 25544 51.6402 129.5626 0021849 53.2994 33.8338 15.60068263744210") self.locate()
def test_github_25(self): if sys.maxsize > 2147483647: # breaks under 64 bits, as on Travis-CI return tle=[ "OBJECT L", "1 39276U 13055L 13275.56815576 .28471697 00000-0 53764+0 0 92", "2 39276 080.9963 312.3419 0479021 141.2713 225.6381 14.71846910 412", ] fenton = ephem.Observer() fenton.long = '-106.673887' fenton.lat = '35.881226' fenton.elevation = 2656 fenton.horizon = math.radians(10) fenton.compute_pressure() sat = ephem.readtle(*tle) fenton.date = datetime.datetime(2013,10,6,0,0,0,0) sat.compute(fenton) # Regex for 32-bit Windows environments in Appveyor rgx = re.compile(r'[C-Z]:.*\\Python[0-9]*') if rgx.search(os.environ.get('PYTHON','')) and os.environ.get('PYTHON_ARCH','')=='32': # Sat.neverup does not throw an exception in Appveyor for # 32-bit Windows, but does everywhere else sat.neverup else: self.assertRaises(RuntimeError, lambda: sat.neverup)
def next_pass(self, datestr=None, convert=True): """ Takes date as string (or defaults to current time) to compute the next closest pass of a satellite for the observer. Times are returned in local time zone, and angles are returned in degrees. :param datestr: string containing date :param convert: whether or not to convert to time string/ angle degrees :return: a dictionary of values """ if datestr is not None: date = parser.parse(datestr) date = date.replace(tzinfo=tz.tzlocal()) dateutc = ephem.Date(str(date.astimezone(tz.tzutc()))) else: dateutc = ephem.Date(str(datetime.utcnow())) observer = ephem.Observer() # create a copy of observer observer.lon = self.observer.lon observer.lat = self.observer.lat observer.elev = self.observer.elev observer.epoch = self.observer.epoch observer.date = ephem.Date(dateutc + ephem.minute) satellite = ephem.readtle(self.tle[0], self.tle[1], self.tle[2]) # make a copy of satellite satellite.compute(observer) next_pass = observer.next_pass(satellite) if convert: next_pass = {'risetime': tolocal(next_pass[0]), 'riseaz': to_degs(next_pass[1]), 'maxtime': tolocal(next_pass[2]) , 'maxalt': to_degs(next_pass[3]), 'settime': tolocal(next_pass[4]), 'setaz': to_degs(next_pass[5])} else: next_pass = {'risetime': next_pass[0], 'riseaz': next_pass[1], 'maxtime': next_pass[2] , 'maxalt': next_pass[3], 'settime': next_pass[4], 'setaz': next_pass[5]} return next_pass
def PassDetails(begin_timestamp, duration_seconds, latitude_degrees, longitude_degrees, elevation_metres, tle, resolution_seconds): obs = ephem.Observer() obs.lat = math.radians(latitude_degrees) obs.lon = math.radians(longitude_degrees) obs.elevation = elevation_metres body = ephem.readtle(*tle) begin_time = ephem.Date(datetime.datetime.utcfromtimestamp(begin_timestamp)) n = int(duration_seconds/resolution_seconds) print n for i in xrange(n): t_offset = i*resolution_seconds timestamp = begin_timestamp + t_offset obs.date = ephem.Date(begin_time + ephem.second*t_offset) body.compute(obs) print '%f %f %f %f %f %f %f %f %d' % ( timestamp, math.degrees(body.az), math.degrees(body.alt), float(body.range), # [m] float(body.range_velocity), # [m/s] math.degrees(body.sublat), math.degrees(body.sublong), float(body.elevation), # [m] bool(body.eclipsed))
def drawIssTrack(self,elements,param=1,n=0,step=1104): st = self.Arrays[19][n] et = self.Arrays[19][n+step] print "Plotting from - ", st, " to ", et cn = int(n + step /2) ct = self.Arrays[19][cn] line1,line2=elements.elemsFromDateString(ct) if (self.chatty): print "drawIssTrack", n,step, ct, line1, line2 for nn in range(n,n+step,6): ntime = self.Arrays[19][nn] #if self.chatty: print ntime tle_rec = ephem.readtle("ISS", line1, line2) tle_rec.compute(ntime) #convert to strings# lat2string = str(tle_rec.sublat) long2string = str(tle_rec.sublong) lati = lat2string.split(":") longt = long2string.split(":") #if self.chatty: print "ISS SUBSURFACE -", lati,longt lat = float(lati[0]) + float(lati[1])/60. + float(lati[2])/3600. lon = float(longt[0]) + float(longt[1])/60. + float(longt[2])/3600. xpt,ypt=self.map(lon,lat) # drawing style kargs = "g+" if (nn == n): plt.text(xpt,ypt,"start") if (nn >= (n+step -6) ): plt.text(xpt,ypt,"end") # make every 5 mins dot if ((nn % 30) == 0): kargs = "g." self.map.plot(xpt,ypt,kargs)
def prediction_path(name, line1, line2): # define variables as lists longitude = [] latitude = [] # define time date_utcnow = datetime.datetime.utcnow() # read TLE data into ephem tle_rec = ephem.readtle(name, line1, line2) # for loop to predict satellite coordinate for 36 hours ahead # start from now (t=0) for t in range(24*60): # interval an hour date_delta = datetime.timedelta(minutes=t) date_prediction = date_utcnow + date_delta # compute TLE data tle_rec.compute(date_prediction) # write the data into lists longitude.append(tle_rec.sublong / ephem.degree) latitude.append(tle_rec.sublat / ephem.degree) # return dictionary (python) or object (JavaScript) return {'latitude': latitude, 'longitude': longitude}
# ------------------------------------------------------- # I import this library to do the magnetic field strength calculations import math # ------------------------------------------------------- """ SET VARIABLE """ # parameter setting for obtaining latitude and longitude name = "ISS (ZARYA)" line1 = "1 25544U 98067A 20316.41516162 .00001589 00000+0 36499-4 0 9995" line2 = "2 25544 51.6454 339.9628 0001882 94.8340 265.2864 15.49409479254842" iss = readtle(name, line1, line2) # ------------------------------------------------------- # parameter setting for time measurement INITIAL_TIME = datetime.datetime.now() # ------------------------------------------------------- # parameter setting for magnetic field detection sensor = SenseHat() # ------------------------------------------------------- # setting parameters to take a photo numberPhoto = 0 camera = PiCamera() camera.resolution = (2592, 1944) TIME_BETWEEN_TWO_SHOTS = 2
import matplotlib.pyplot as plt from astropy.wcs import WCS from datetime import datetime, timedelta import ephem import time from datetime import datetime, timedelta import math import numpy as np #the below is the TLE of the satellite line1 = "SAT" line2 = "1 25288U 98021D 14349.31528324 .00000635 00000-0 21971-3 0 9991" line3 = "2 25288 086.3976 246.2475 0002242 098.2459 040.7746 14.34226918873885" sat = ephem.readtle(line1, line2, line3) #The below section sets the MWA as the observer mwa = ephem.Observer() mwa.lon = '116:40:14.93485' mwa.lat = '-26:42:11.94986' mwa.elevation = 377.827 #from sea level time_delay_array = np.linspace(-300, 90, 500) hfont = {'fontname': 'Helvetica', 'size': 15} i = 28 hdu1 = fits.open('1102604896-2m-' + str(i * 2) + '-0654-image.fits') hdu2 = fits.open('1102604896-2m-' + str(i * 2 + 2) + '-0654-image.fits')
while True: # Connects to TCP-socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((IPV4, PORT)) s.listen(1) conn, addr = s.accept() with conn: print('Client connected from, ', addr) Line1 = (conn.recv(1024)).decode() Line2 = (conn.recv(1024)).decode() Line3 = (conn.recv(1024)).decode() try: # Creates TLE set from the three lines sent thorugh TCP-socket tle_sat = ephem.readtle(Line1, Line2, Line3) tle_sat.compute() except ValueError as err: print( f'Invalid TLE, error: \"{err}\".\nPlease check custom TLE and rerun \"Track.py\".' ) break # Creates map and appends it a title my_map = Basemap(projection='cyl', resolution='c', area_thresh=1000.0, lat_0=0, lon_0=0) figure = my_map title = 'Currently tracking: ' + tle_sat.name + ', 90min prediction'
def pass_predictions(request, id): """Endpoint for pass predictions""" station = get_object_or_404(Station, id=id) unsupported_frequencies = request.GET.get('unsupported_frequencies', '0') try: satellites = Satellite.objects.filter(transmitters__alive=True) \ .filter(status='alive').distinct() except Satellite.DoesNotExist: pass # we won't have any next passes to display # Load the station information and invoke ephem so we can # calculate upcoming passes for the station observer = ephem.Observer() observer.lon = str(station.lng) observer.lat = str(station.lat) observer.elevation = station.alt nextpasses = [] passid = 0 for satellite in satellites: # look for a match between transmitters from the satellite and # ground station antenna frequency capabilities if int(unsupported_frequencies) == 0: frequency_supported = False transmitters = Transmitter.objects.filter(satellite=satellite) for gs_antenna in station.antenna.all(): for transmitter in transmitters: if transmitter.downlink_low: if (gs_antenna.frequency <= transmitter.downlink_low <= gs_antenna.frequency_max): frequency_supported = True if not frequency_supported: continue observer.date = ephem.date(datetime.today()) try: sat_ephem = ephem.readtle(str(satellite.latest_tle.tle0), str(satellite.latest_tle.tle1), str(satellite.latest_tle.tle2)) except (ValueError, AttributeError): continue # Here we are going to iterate over each satellite to # find its appropriate passes within a given time constraint keep_digging = True while keep_digging: try: tr, azr, tt, altt, ts, azs = observer.next_pass(sat_ephem) except ValueError: break # there will be sats in our list that fall below horizon, skip except TypeError: break # if there happens to be a non-EarthSatellite object in the list except Exception: break if tr is None: break # using the angles module convert the sexagesimal degree into # something more easily read by a human try: elevation = format(math.degrees(altt), '.0f') azimuth_r = format(math.degrees(azr), '.0f') azimuth_s = format(math.degrees(azs), '.0f') except TypeError: break passid += 1 # show only if >= configured horizon and in next 6 hours, # and not directly overhead (tr < ts see issue 199) if tr < ephem.date(datetime.today() + timedelta(hours=settings.STATION_UPCOMING_END)): if (float(elevation) >= station.horizon and tr < ts): valid = True if tr < ephem.Date(datetime.now() + timedelta(minutes=settings.OBSERVATION_DATE_MIN_START)): valid = False polar_data = calculate_polar_data(observer, sat_ephem, tr.datetime(), ts.datetime(), 10) sat_pass = {'passid': passid, 'mytime': str(observer.date), 'name': str(satellite.name), 'id': str(satellite.id), 'success_rate': str(satellite.success_rate), 'unknown_rate': str(satellite.unknown_rate), 'bad_rate': str(satellite.bad_rate), 'data_count': str(satellite.data_count), 'good_count': str(satellite.good_count), 'bad_count': str(satellite.bad_count), 'unknown_count': str(satellite.unknown_count), 'norad_cat_id': str(satellite.norad_cat_id), 'tr': tr.datetime(), # Rise time 'azr': azimuth_r, # Rise Azimuth 'tt': tt.datetime(), # Max altitude time 'altt': elevation, # Max altitude 'ts': ts.datetime(), # Set time 'azs': azimuth_s, # Set azimuth 'valid': valid, 'polar_data': polar_data} nextpasses.append(sat_pass) observer.date = ephem.Date(ts).datetime() + timedelta(minutes=1) else: keep_digging = False data = { 'id': id, 'nextpasses': sorted(nextpasses, key=itemgetter('tr')) } return JsonResponse(data, safe=False)
def test_distance_between_satellites(self): kuiper_satellite_0 = ephem.readtle( "Kuiper-630 0", "1 00001U 00000ABC 00001.00000000 .00000000 00000-0 00000+0 0 04", "2 00001 51.9000 0.0000 0000001 0.0000 0.0000 14.80000000 02" ) kuiper_satellite_1 = ephem.readtle( "Kuiper-630 1", "1 00002U 00000ABC 00001.00000000 .00000000 00000-0 00000+0 0 05", "2 00002 51.9000 0.0000 0000001 0.0000 10.5882 14.80000000 07" ) kuiper_satellite_17 = ephem.readtle( "Kuiper-630 17", "1 00018U 00000ABC 00001.00000000 .00000000 00000-0 00000+0 0 02", "2 00018 51.9000 0.0000 0000001 0.0000 180.0000 14.80000000 09" ) kuiper_satellite_18 = ephem.readtle( "Kuiper-630 18", "1 00019U 00000ABC 00001.00000000 .00000000 00000-0 00000+0 0 03", "2 00019 51.9000 0.0000 0000001 0.0000 190.5882 14.80000000 04" ) kuiper_satellite_19 = ephem.readtle( "Kuiper-630 19", "1 00020U 00000ABC 00001.00000000 .00000000 00000-0 00000+0 0 05", "2 00020 51.9000 0.0000 0000001 0.0000 201.1765 14.80000000 05" ) for extra_time_ns in [ 0, # 0 1, # 1ns 1000, # 1 microsecond 1000000, # 1ms 1000000000, # 1s 60000000000, # 60s 10 * 60000000000, # 10 minutes 20 * 60000000000, # 20 minutes 30 * 60000000000, # 30 minutes 40 * 60000000000, # 40 minutes 50 * 60000000000, # 50 minutes 60 * 60000000000, # 60 minutes 70 * 60000000000, # 70 minutes 80 * 60000000000, # 80 minutes 90 * 60000000000, # 90 minutes 100 * 60000000000, # 100 minutes ]: epoch = Time("2000-01-01 00:00:00", scale="tdb") time = epoch + extra_time_ns * u.ns # Distance to themselves should always be zero self.assertEqual( distance_m_between_satellites(kuiper_satellite_0, kuiper_satellite_0, str(epoch), str(time)), 0 ) self.assertEqual( distance_m_between_satellites(kuiper_satellite_1, kuiper_satellite_1, str(epoch), str(time)), 0 ) self.assertEqual( distance_m_between_satellites(kuiper_satellite_17, kuiper_satellite_17, str(epoch), str(time)), 0 ) self.assertEqual( distance_m_between_satellites(kuiper_satellite_18, kuiper_satellite_18, str(epoch), str(time)), 0 ) # Distances should not matter if (a, b) or (b, a) self.assertEqual( distance_m_between_satellites(kuiper_satellite_0, kuiper_satellite_1, str(epoch), str(time)), distance_m_between_satellites(kuiper_satellite_1, kuiper_satellite_0, str(epoch), str(time)), ) self.assertEqual( distance_m_between_satellites(kuiper_satellite_1, kuiper_satellite_17, str(epoch), str(time)), distance_m_between_satellites(kuiper_satellite_17, kuiper_satellite_1, str(epoch), str(time)), ) self.assertEqual( distance_m_between_satellites(kuiper_satellite_19, kuiper_satellite_17, str(epoch), str(time)), distance_m_between_satellites(kuiper_satellite_17, kuiper_satellite_19, str(epoch), str(time)), ) # Distance between 0 and 1 should be less than between 0 and 18 (must be on other side of planet) self.assertGreater( distance_m_between_satellites(kuiper_satellite_0, kuiper_satellite_18, str(epoch), str(time)), distance_m_between_satellites(kuiper_satellite_0, kuiper_satellite_1, str(epoch), str(time)), ) # Triangle inequality self.assertGreater( distance_m_between_satellites(kuiper_satellite_17, kuiper_satellite_18, str(epoch), str(time)) + distance_m_between_satellites(kuiper_satellite_18, kuiper_satellite_19, str(epoch), str(time)), distance_m_between_satellites(kuiper_satellite_17, kuiper_satellite_19, str(epoch), str(time)) ) # Earth radius = 6378135 m # Kuiper altitude = 630 km # So, the circle is 630000 + 6378135 = 7008135 m in radius # As such, with 34 satellites, the side of this 34-polygon is: polygon_side_m = 2 * (7008135.0 * math.sin(math.radians(360.0 / 33.0) / 2.0)) self.assertTrue( polygon_side_m >= distance_m_between_satellites( kuiper_satellite_17, kuiper_satellite_18, str(epoch), str(time) ) >= 0.9 * polygon_side_m ) self.assertTrue( polygon_side_m >= distance_m_between_satellites( kuiper_satellite_18, kuiper_satellite_19, str(epoch), str(time) ) >= 0.9 * polygon_side_m ) self.assertTrue( polygon_side_m >= distance_m_between_satellites( kuiper_satellite_0, kuiper_satellite_1, str(epoch), str(time) ) >= 0.9 * polygon_side_m )
import ephem import numpy as np from rtlsdr import RtlSdr from scipy.io import savemat from helpers import get_tle_lines from sat_db import active_orbcomm_satellites from CONFIG import * # Create a pyephem sat object for all the active satellites # using latest TLE data for name in active_orbcomm_satellites: sat_line0, sat_line1, sat_line2 = get_tle_lines(name, tle_dir='./tles') sat = ephem.readtle(sat_line0, sat_line1, sat_line2) active_orbcomm_satellites[name]['sat_obj'] = sat active_orbcomm_satellites[name]['tles'] = [sat_line0, sat_line1, sat_line2] # PyEphem observer # set lat/long/alt in the CONFIG file obs = ephem.Observer() obs.lat, obs.lon = '{}'.format(lat), '{}'.format(lon) obs.elevation = alt # Technically is the altitude of observer # Set RTLSDR parameters and initialize sample_rate = 1.2288e6 center_freq = 137.5e6 gain = 'auto' # Use AGC sdr = RtlSdr()
import math import time from datetime import datetime import ephem degrees_per_radian = 180.0 / math.pi home = ephem.Observer() home.lon = '-81.174415' # +E home.lat = '42.593948' # +N home.elevation = 80 # meters # Always get the latest ISS TLE data from: # http://spaceflight.nasa.gov/realdata/sightings/SSapplications/Post/JavaSSOP/orbit/ISS/SVPOST.html iss = ephem.readtle( 'ISS', '1 25544U 98067A 19093.54651620 .00001767 00000-0 35856-4 0 9993', '2 25544 51.6445 12.2674 0002441 141.3518 216.2348 15.52476822163652') while True: home.date = datetime.utcnow() iss.compute(home) print('iss: altitude %4.1f deg, azimuth %5.1f deg' % (iss.alt * degrees_per_radian, iss.az * degrees_per_radian)) time.sleep(1.0)
import ephem import datetime name = "NOAA 17" line1 = "1 27453U 02032A 20117.76856472 .00000011 00000-0 23213-4 0 9991" line2 = "2 27453 98.5799 65.4278 0012367 32.9042 327.2905 14.25064027927547" tle_rec = ephem.readtle(name, line1, line2) tle_rec.compute() print(tle_rec.sublong, tle_rec.sublat)
def __init__(self, tle): self.name, self.line1, self.line2 = tle.split('\n') self._obj = ephem.readtle(self.name, self.line1, self.line2)
def main(): line0 = 'ISS (ZARYA)' line1 = '1 25544U 98067A 16045.08461514 .00015278 00000-0 23253-3 0 9996' line2 = '2 25544 51.6435 316.9119 0006811 112.2536 34.0677 15.5475799985676' tracker = ephem.Observer() tracker.lat = '39.16532' tracker.long = '-86.52639' target = 0 targetAz = 0 targetElev = 0 tracker.elevation = 152 # tracker.date = str(currentTime.tm_year) + "/" + str(currentTime.tm_mon) + "/" + str(currentTime.tm_mday) + " " + str(currentTime.tm_hour + 1) +":"+ str(currentTime.tm_min) + ":" + str(currentTime.tm_sec) print "TRACKER INFORMATION --------------" print tracker.date, tracker.lat, tracker.long print "ISS INFORMATION -----------------------" iss= ephem.readtle(line0, line1, line2) iss.compute() print iss.sublat, iss.sublong sun = ephem.Sun() sun.compute() moon = ephem.Moon() moon.compute() while True: # now = time.time() # currentTime = time.localtime() # tracker.date = str(currentTime.tm_year) + "/" + str(currentTime.tm_mon) + "/" + str(currentTime.tm_mday) + " " + str(currentTime.tm_hour) +":"+ str(currentTime.tm_min) + ":" + str(currentTime.tm_sec) tracker = ephem.Observer() tracker.lat = '39.16532' tracker.long = '-86.52639' tracker.elevation = 152 if target ==0: print "ISS RELATIVE TO TRACKER ---------------" iss.compute(tracker) print iss.sublat, iss.sublong print iss.alt, iss.az targetAz = iss.az targetElev = iss.alt if target == 1: print "Sun RELATIVE TO TRACKER ---------------" sun.compute(tracker) # print sun.sublat, sun.sublong print sun.alt, sun.az targetAz = sun.az targetElev = sun.alt if target == 2: print "Moon RELATIVE TO TRACKER ---------------" moon.compute(tracker) # print sun.sublat, sun.sublong print moon.alt, moon.az targetAz = moon.az targetElev = moon.alt if target == 3: print "RESET RELATIVE TO TRACKER ---------------" # sun.compute(tracker) # print sun.sublat, sun.sublong print 0, 0 targetAz = 0 targetElev = 0 print "bits ready: ", s.inWaiting() if s.inWaiting(): target = int(s.read(1)) print target print target sendToPic(targetAz, targetElev)
from picamera import PiCamera from datetime import datetime import time import os from os.path import split from os.path import isdir import ephem iss = ephem.readtle(nazwa, linijka1, linijka2) def angle2exifRef(issAngle, directions): issLonstr = str(issAngle).split(':') issLonAngle2 = [float(z) for z in issLonstr] if issLonAngle2[0] < 0: return directions[0] else: return directions[1] def angle2exif(issLon): isssublong = str(issLon).split(':') isssublong = [float(i) for i in isssublong] return na_ulamki(isssublong) name = 'ISS (ZARYA)' line1 = '1 25544U 98067A 20014.55106447 .00001081 00000-0 27319-4 0 9995' line2 = '2 25544 51.6449 33.6082 0005001 130.1836 8.0955 15.49563139208048' iss = ephem.readtle(name, line1, line2)
def test_distance_ground_station_to_satellite(self): epoch = Time("2000-01-01 00:00:00", scale="tdb") time = epoch + 100 * 1000 * 1000 * 1000 * u.ns # Two satellites telesat_18 = ephem.readtle( "Telesat-1015 18", "1 00019U 00000ABC 00001.00000000 .00000000 00000-0 00000+0 0 03", "2 00019 98.9800 13.3333 0000001 0.0000 152.3077 13.66000000 04" ) telesat_19 = ephem.readtle( "Telesat-1015 19", "1 00020U 00000ABC 00001.00000000 .00000000 00000-0 00000+0 0 05", "2 00020 98.9800 13.3333 0000001 0.0000 180.0000 13.66000000 00" ) # Their shadows shadow_18 = create_basic_ground_station_for_satellite_shadow(telesat_18, str(epoch), str(time)) shadow_19 = create_basic_ground_station_for_satellite_shadow(telesat_19, str(epoch), str(time)) # Distance to shadow should be around 1015km self.assertAlmostEqual( distance_m_ground_station_to_satellite(shadow_18, telesat_18, str(epoch), str(time)), 1015000, # 1015km delta=5000 # Accurate within 5km ) distance_shadow_19_to_satellite_19 = distance_m_ground_station_to_satellite( shadow_19, telesat_19, str(epoch), str(time) ) self.assertAlmostEqual( distance_shadow_19_to_satellite_19, 1015000, # 1015km delta=5000 # Accurate within 5km ) # Distance between the two shadows: # 21.61890110054602, 96.54190305000301 # -5.732296878862085, 92.0396062736707 shadow_distance_m = geodesic_distance_m_between_ground_stations(shadow_18, shadow_19) self.assertAlmostEqual( shadow_distance_m, 3080640, # 3080.64 km, from Google Maps delta=5000 # With an accuracy of 5km ) # The Pythagoras distance must be within 10% assuming the geodesic does not cause to much of an increase distance_shadow_18_to_satellite_19 = distance_m_ground_station_to_satellite( shadow_18, telesat_19, str(epoch), str(time) ) self.assertAlmostEqual( math.sqrt(shadow_distance_m ** 2 + distance_shadow_19_to_satellite_19 ** 2), distance_shadow_18_to_satellite_19, delta=0.1 * math.sqrt(shadow_distance_m ** 2 + distance_shadow_19_to_satellite_19 ** 2) ) # Check that the hypotenuse is not exceeded straight_shadow_distance_m = straight_distance_m_between_ground_stations(shadow_18, shadow_19) self.assertGreater( distance_shadow_18_to_satellite_19, math.sqrt( straight_shadow_distance_m ** 2 + distance_shadow_19_to_satellite_19 ** 2 ), ) # Check what happens with cartesian coordinates a = geodetic2cartesian( float(shadow_18["latitude_degrees_str"]), float(shadow_18["longitude_degrees_str"]), shadow_18["elevation_m_float"], ) b = geodetic2cartesian( float(shadow_19["latitude_degrees_str"]), float(shadow_19["longitude_degrees_str"]), shadow_19["elevation_m_float"], ) # For now, we will keep a loose bound of 1% here, but it needs to be tightened # It mostly has to do with that the great circle does not account for the ellipsoid effect self.assertAlmostEqual( math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2), straight_shadow_distance_m, delta=20000 # 20km )
print(t) f = open("LEOtle.txt") line = f.readline() counter = 1 line1 = "starlink" while line: if counter % 2 == 1: line2 = line else: line3 = line satID = int(line2[2] + line2[3] + line2[4] + line2[5] + line2[6]) #print(satID) if satID not in sat_id_array: sat_id_array.append(satID) #print("appended") sat = ephem.readtle(str(line1), str(line2), str(line3)) sat.compute(mwa) x, y = wcs.all_world2pix( [[np.degrees(sat.ra.real), np.degrees(sat.dec.real)]], 1)[0] #except: # print("could not calculate") # counter +=1 # line = f.readline() # continue #print("could calculate tle") if (5 <= x <= 1995) and (5 <= y < 1995): #print("plotting trail...") #plt.plot(x,y,marker='+',color='blue',markersize='0.25') LeoData[int(y), int(x)] = 1 LeoData[int(y + 1), int(x)] = 1
# Connect to the Sense Hat sense = SenseHat() # Set the led light to low sense.low_light = True # Set a logfile name logfile(dir_path + "/astrovitruvio.log") # Latest TLE data for ISS location # Please update these values with the latest ones before running our program, thank you name = "ISS (ZARYA)" l1 = "1 25544U 98067A 19336.91239465 -.00004070 00000-0 -63077-4 0 9991" l2 = "2 25544 51.6431 244.7958 0006616 354.0287 44.0565 15.50078860201433" iss = readtle(name, l1, l2) def create_csv_file(data_file): "Create a new CSV file and add the header row" with open(data_file, 'w') as f: writer = csv.writer(f) header = ("Date/time", "magx", "magy", "magz", "lat", "long", "gpitch", "groll", "gyaw") writer.writerow(header) def add_csv_data(data_file, data): "Add a row of data to the data_file CSV" with open(data_file, 'a') as f: writer = csv.writer(f)
def __init__(self, name, l1, l2): self.e = ephem.readtle(name, l1, l2)
if (RAsun < -180 + RA0): RAsun += 360 RAsuns, Decsuns = sunpositions() RAsuns = numpy.array(RAsuns) Decsuns = numpy.array(Decsuns) #HAsuns=RAsuns-LST_hours*15 HAsuns = -RAsuns + LST_hours * 15 RAsuns = numpy.where(RAsuns > 180 + RA0, RAsuns - 360, RAsuns) RAsuns = numpy.where(RAsuns < -180 + RA0, RAsuns + 360, RAsuns) ra_sat = [] dec_sat = [] time_sat = [] if tlelines is not None and len(tlelines) >= 3: satellite_label = tlelines[0].replace('_', '\_').replace('\n', '') satellite = ephem.readtle(tlelines[0], tlelines[1], tlelines[2]) compute_time0 = datetime.datetime(year=yr, month=mn, day=dy, hour=int(hour), minute=int(minute), second=int(second)) ra_sat, dec_sat, time_sat, sublong_sat, sublat_sat = satellite_positions( satellite, observer, compute_time0, range(0, duration, 1), RA0=RA0) # do the plotting # this sets up the figure with the right aspect ratio fig = pylab.figure(figsize=(figsize, 0.5 * figsize), dpi=120) ax1 = fig.add_subplot(1, 1, 1) # this is the Haslam map, plotted as a log-scale # it is slightly transparent since this does below the horizon too
def find_iss(self, iss_tle): iss = ephem.readtle(iss_tle[0], iss_tle[1], iss_tle[2]) self.site.date = datetime.utcnow() iss.compute(self.site) return iss
from json import dumps, load degrees_per_radian = 180.0 / math.pi #### set Observer #observer = ephem.Observer() #observer.lon = '-122.63' # +E #observer.lat = '45.56' # +N #observer.elevation = 80 # meters observer = ephem.city("Paris") #### read Two Line Element Data # NORAD Two-Line Element Sets # http://celestrak.com/NORAD/elements/ celestialBody = ephem.readtle('APRIZESAT 2', '1 28366U 04025A 14271.35446003 .00000272 00000-0 10088-3 0 8693', '2 28366 98.3090 201.2758 0109272 140.4396 220.4831 14.36260423537050' ) #### compute position of Celestial Body relative to Observer while True: observer.date = datetime.utcnow() celestialBody.compute(observer) elevationPosition = celestialBody.alt * degrees_per_radian azimuthPosition = celestialBody.az * degrees_per_radian print ('%s position, measured from %s: azimuth: %s; elevation: %s; distance: %s;' % (celestialBody.name, observer.name, azimuthPosition, elevationPosition, celestialBody.range)) with open("data.json", "w") as file: file.write(dumps({'body':celestialBody.name, 'azimuth':azimuthPosition, 'elevation':elevationPosition, 'distance':celestialBody.range}, file, indent=4)) print ('Writing JSON file:') with open("data.json", "r") as file:
import ephem from picamera import PiCamera from pathlib import Path dir_path = Path(__file__).parent.resolve() name = "ISS (ZARYA)" line1 = "1 25544U 98067A 20316.41516162 .00001589 00000+0 36499-4 0 9995" line2 = "2 25544 51.6454 339.9628 0001882 94.8340 265.2864 15.49409479254842" iss = ephem.readtle(name, line1, line2) cam = PiCamera() cam.resolution = (1296,972) # Valid resolution for V1 camera iss.compute() def convert(angle): """ Convert an ephem angle (degrees:minutes:seconds) to an EXIF-appropriate representation (rationals) e.g. '51:35:19.7' to '51/1,35/1,197/10' Return a tuple containing a boolean and the converted angle, with the boolean indicating if the angle is negative. """ degrees, minutes, seconds = (float(field) for field in str(angle).split(":")) exif_angle = f'{abs(degrees):.0f}/1,{minutes:.0f}/1,{seconds*10:.0f}/10' return degrees < 0, exif_angle def capture(camera, image): """Use `camera` to capture an `image` file with lat/long EXIF data.""" iss.compute() # Get the lat/long values from ephem
def iss(self): return ephem.readtle(self.name, self.line1, self.line2)
import zad1 from ephem import readtle, degree from datetime import datetime, timezone name = 'ISS zayra' p1 = "1 25544U 98067A 20347.38065972 .00001339 00000-0 32251-4 0 9999" p2 = "2 25544 51.6440 186.7650 0001859 122.9504 239.1247 15.49179161259649" iss = readtle(name, p1, p2) pos_lat = (zad1.angle2exif(str(iss.sublat))) pos_lon = (zad1.angle2exif(str(iss.sublon))) if pos_lat[0] == True: hemisphere = 'N' else: hemisphere = 'S'
def do_best_beams(values, beamsfile, return_all = False): bests = [] source = pyproj.Proj(init='epsg:4326') target = pyproj.Proj(proj='geocent') for vs in values: lat, lon = vs[:2] try: date = ephem.Date(vs[2]) except IndexError: date = ephem.now() obs = ephem.Observer() obs.lat = str(lat) obs.lon = str(lon) obs.date = date obs_xyz = pyproj.transform(source, target, x=obs.lon * 180. / ephem.pi, y=obs.lat * 180. / ephem.pi, z=obs.elevation) bbs = [] best = None for label, tlepath in constellation.items(): f = beamsfile sat_beams = parse_beam_data(f.readlines(), label) tle = load_tle(tlepath, url='http://www.celestrak.com/NORAD/elements/geo.txt') #tle = open(tlepath).readlines() #sat = ephem.readtle(*tle) sat = ephem.readtle(tle[0], tle[1], tle[2]) sat.compute(obs) sat_xyz = pyproj.transform(source, target, x=sat.sublong * 180. / ephem.pi, y=sat.sublat * 180. / ephem.pi, z=sat.elevation) sat_best_beams = closest_beams(float(lat), float(lon), sat_beams, max_beams) #1.66e9 is the satellite frequency in Hertz db_beam_losses(obs_xyz, sat_xyz, sat_best_beams, 1.66e9, 3.0) if return_all == False: sat_best_beams = sorted(sat_best_beams, key=lambda b: -b[6]) bb = sat_best_beams[0] if return_all == True: for sbb in sat_best_beams: bbs.append((float(lat), float(lon), date.datetime().isoformat(), sbb, sat.alt)) else: if 0 < sat.alt < 180 and (bb[6] > best or best == None): best = bb[6] bbs.append((float(lat), float(lon), date.datetime().isoformat(), bb, sat.alt)) #print "Best match is " + bb[5] + " - Beam: " + str(bb[1]) + " - Point: " + str(bb[2]) #print "Arc distance from beam point is " + str(round(bb[0]/1000, 3)) + " km" #print "Elevation is " + str(round(sat.alt, 2)) + " degrees" #print "Attenuation is " + str(round(bb[6], 2)) + " dB" #print "Signal power efficiency is " + str(round(bb[7]*100, 2)) + "% of power at beam center" if len(bbs) == 0: print "No available satellite found" else: if return_all: bests.append(bbs) else: bests.append(bbs[-1]) return bests
def allTLE(self, url): TLEs = [] s = self.readTLE(url) for element in s: TLEs.append(ephem.readtle(element[0], element[1], element[2])) return TLEs
def observation_new(request): """View for new observation""" me = request.user can_schedule = schedule_perms(me) if not can_schedule: messages.error(request, 'You don\'t have permissions to schedule observations') return redirect(reverse('base:observations_list')) if request.method == 'POST': sat_id = request.POST.get('satellite') trans_id = request.POST.get('transmitter') try: start_time = datetime.strptime(request.POST.get('start-time'), '%Y-%m-%d %H:%M') end_time = datetime.strptime(request.POST.get('end-time'), '%Y-%m-%d %H:%M') except ValueError: messages.error(request, 'Please use the datetime dialogs to submit valid values.') return redirect(reverse('base:observation_new')) if (end_time - start_time) > timedelta(minutes=settings.OBSERVATION_DATE_MAX_RANGE): messages.error(request, 'Please use the datetime dialogs to submit valid timeframe.') return redirect(reverse('base:observation_new')) if (start_time < datetime.now()): messages.error(request, 'Please schedule an observation that begins in the future') return redirect(reverse('base:observation_new')) start = make_aware(start_time, utc) end = make_aware(end_time, utc) sat = Satellite.objects.get(norad_cat_id=sat_id) trans = Transmitter.objects.get(uuid=trans_id) tle = Tle.objects.get(id=sat.latest_tle.id) sat_ephem = ephem.readtle(str(sat.latest_tle.tle0), str(sat.latest_tle.tle1), str(sat.latest_tle.tle2)) observer = ephem.Observer() observer.date = str(start) total = int(request.POST.get('total')) scheduled = [] for item in range(total): start = datetime.strptime( request.POST.get('{0}-starting_time'.format(item)), '%Y-%m-%d %H:%M:%S.%f' ) end = datetime.strptime( request.POST.get('{}-ending_time'.format(item)), '%Y-%m-%d %H:%M:%S.%f' ) station_id = request.POST.get('{}-station'.format(item)) ground_station = Station.objects.get(id=station_id) observer.lon = str(ground_station.lng) observer.lat = str(ground_station.lat) observer.elevation = ground_station.alt tr, azr, tt, altt, ts, azs = observer.next_pass(sat_ephem) obs = Observation(satellite=sat, transmitter=trans, tle=tle, author=me, start=make_aware(start, utc), end=make_aware(end, utc), ground_station=ground_station, rise_azimuth=format(math.degrees(azr), '.0f'), max_altitude=format(math.degrees(altt), '.0f'), set_azimuth=format(math.degrees(azs), '.0f')) obs.save() scheduled.append(obs.id) time_start_new = ephem.Date(ts).datetime() + timedelta(minutes=1) observer.date = time_start_new.strftime("%Y-%m-%d %H:%M:%S.%f") try: del request.session['scheduled'] except KeyError: pass request.session['scheduled'] = scheduled # If it's a single observation redirect to that one if total == 1: messages.success(request, 'Observation was scheduled successfully.') return redirect(reverse('base:observation_view', kwargs={'id': scheduled[0]})) messages.success(request, 'Observations were scheduled successfully.') return redirect(reverse('base:observations_list')) satellites = Satellite.objects.filter(transmitters__alive=True) \ .filter(status='alive').distinct() transmitters = Transmitter.objects.filter(alive=True) obs_filter = {} if request.method == 'GET': filter_form = SatelliteFilterForm(request.GET) if filter_form.is_valid(): start_date = filter_form.cleaned_data['start_date'] end_date = filter_form.cleaned_data['end_date'] ground_station = filter_form.cleaned_data['ground_station'] norad = filter_form.cleaned_data['norad'] if start_date: start_date = datetime.strptime(start_date, '%Y/%m/%d %H:%M').strftime('%Y-%m-%d %H:%M') if end_date: end_date = (datetime.strptime(end_date, '%Y/%m/%d %H:%M') + timedelta(minutes=1)).strftime('%Y-%m-%d %H:%M') obs_filter['exists'] = True obs_filter['norad'] = norad obs_filter['start_date'] = start_date obs_filter['end_date'] = end_date if ground_station: obs_filter['ground_station'] = ground_station else: obs_filter['exists'] = False return render(request, 'base/observation_new.html', {'satellites': satellites, 'transmitters': transmitters, 'obs_filter': obs_filter, 'date_min_start': settings.OBSERVATION_DATE_MIN_START, 'date_min_end': settings.OBSERVATION_DATE_MIN_END, 'date_max_range': settings.OBSERVATION_DATE_MAX_RANGE})
def map_plot(self, time, TLE): start_mode = self.mode_choice.GetSelection() m = Basemap(projection='mill', area_thresh=1000.0, llcrnrlat=south, urcrnrlat=north, llcrnrlon=west, urcrnrlon=east) #m.shadedrelief() im = Image.open(resource_path('default_map.png')) m.imshow(im, alpha=1) m.nightshade(time + datetime.timedelta(hours=10)) #m.drawcoastlines() # 一分ごとの人工衛星の位置をプロット time_list = [] for t in range(-10, 100): time_list.append(time + datetime.timedelta(minutes=t)) for t in time_list: satellite = ephem.readtle(TLE[0], TLE[1], TLE[2]) satellite.compute(t) latitude = satellite.sublat / ephem.degree longitude = satellite.sublong / ephem.degree - 150 if longitude < -180: longitude += 360 x1, y1 = m(longitude, latitude) m.plot(x1, y1, marker=".", markersize=1, c='blue') if self.mode_choice.GetSelection() != start_mode: if self.mode_choice.GetSelection(): time = datetime.datetime.utcnow() else: time = self.get_time() self.map_plot(time, TLE) return 0 satellite = ephem.readtle(TLE[0], TLE[1], TLE[2]) satellite.compute(time) latitude = satellite.sublat / ephem.degree longitude = satellite.sublong / ephem.degree - 150 if longitude < -180: longitude += 360 earth_radius = 6371000. sat_loc = (latitude, longitude) # define the position of the satellite orbit = Orbital(TLE[0], line1=TLE[1], line2=TLE[2]) lon_dum, lat_dum, altitude = orbit.get_lonlatalt(time) print(altitude) position = [altitude * 1000, latitude, longitude] radius = math.degrees( math.acos(earth_radius / (earth_radius + position[0]))) print(longitude) x1, y1 = m(longitude, latitude) m.plot(x1, y1, marker="*", markersize=5, c='red') if longitude < -90: diff = longitude - (-180) m = Basemap(projection='mill', area_thresh=1000.0, llcrnrlat=south, urcrnrlat=north, llcrnrlon=0, urcrnrlon=360) m.tissot(diff, latitude, radius, 100, facecolor='white', alpha=0.5) m = Basemap(projection='mill', area_thresh=1000.0, llcrnrlat=south, urcrnrlat=north, llcrnrlon=-360, urcrnrlon=0) m.tissot(diff, latitude, radius, 100, facecolor='white', alpha=0.5) elif longitude > 90: diff = longitude - 180 m = Basemap(projection='mill', area_thresh=1000.0, llcrnrlat=south, urcrnrlat=north, llcrnrlon=0, urcrnrlon=360) m.tissot(diff, latitude, radius, 100, facecolor='white', alpha=0.5) m = Basemap(projection='mill', area_thresh=1000.0, llcrnrlat=south, urcrnrlat=north, llcrnrlon=-360, urcrnrlon=0) m.tissot(diff, latitude, radius, 100, facecolor='white', alpha=0.5) else: m.tissot(longitude, latitude, radius, 100, facecolor='white', alpha=0.5) plt.gca().spines['right'].set_visible(False) plt.gca().spines['top'].set_visible(False) plt.gca().spines['left'].set_visible(False) plt.gca().spines['bottom'].set_visible(False) plt.subplots_adjust(left=0, right=1, bottom=0, top=1) buf = io.BytesIO() plt.savefig(buf, format='png', dpi=300, transparent=False, bbox_inches='tight', pad_inches=0) #plt.savefig('map.png',format='png', dpi = 600, transparent = False, bbox_inches = 'tight', pad_inches = 0) plt.close() buf.seek(0) self.output_map = buf if self.mode_choice.GetSelection() != start_mode: if self.mode_choice.GetSelection(): time = datetime.datetime.utcnow() else: time = self.get_time() self.map_plot(time, TLE) return 0 self.Image = wx.Image(buf, wx.BITMAP_TYPE_ANY) self.wxImage = wx.Bitmap(self.Image) #画像リサイズ対象=wx.Bitmap self.wxImage_re = scale_bitmap(self.wxImage, int(16 * self.ratio), int(9 * self.ratio)) self.tracking_map.SetBitmap(self.wxImage_re)
def prediction_windows(request, sat_id, transmitter, start_date, end_date, station_id=None): try: sat = Satellite.objects.filter(transmitters__alive=True) \ .filter(status='alive').distinct().get(norad_cat_id=sat_id) except Satellite.DoesNotExist: data = { 'error': 'You should select a Satellite first.' } return JsonResponse(data, safe=False) try: satellite = ephem.readtle( str(sat.latest_tle.tle0), str(sat.latest_tle.tle1), str(sat.latest_tle.tle2) ) except (ValueError, AttributeError): data = { 'error': 'No TLEs for this satellite yet.' } return JsonResponse(data, safe=False) try: downlink = Transmitter.objects.get(uuid=transmitter).downlink_low except Transmitter.DoesNotExist: data = { 'error': 'You should select a Transmitter first.' } return JsonResponse(data, safe=False) end_date = datetime.strptime(end_date, '%Y-%m-%d %H:%M') data = [] stations = Station.objects.all() if station_id: stations = stations.filter(id=station_id) for station in stations: if not schedule_perms(request.user, station): continue # Skip if this station is not capable of receiving the frequency if not downlink: continue frequency_supported = False for gs_antenna in station.antenna.all(): if (gs_antenna.frequency <= downlink <= gs_antenna.frequency_max): frequency_supported = True if not frequency_supported: continue observer = ephem.Observer() observer.lon = str(station.lng) observer.lat = str(station.lat) observer.elevation = station.alt observer.date = str(start_date) station_match = False keep_digging = True while keep_digging: try: tr, azr, tt, altt, ts, azs = observer.next_pass(satellite) except ValueError: data = { 'error': 'That satellite seems to stay always below your horizon.' } break # no match if the sat will not rise above the configured min horizon elevation = format(math.degrees(altt), '.0f') if float(elevation) >= station.horizon: if ephem.Date(tr).datetime() < end_date: if ephem.Date(ts).datetime() > end_date: ts = end_date keep_digging = False else: time_start_new = ephem.Date(ts).datetime() + timedelta(minutes=1) observer.date = time_start_new.strftime("%Y-%m-%d %H:%M:%S.%f") # Adjust or discard window if overlaps exist window_start = make_aware(ephem.Date(tr).datetime(), utc) window_end = make_aware(ephem.Date(ts).datetime(), utc) # Check if overlaps with existing scheduled observations gs_data = Observation.objects.filter(ground_station=station) window = resolve_overlaps(station, gs_data, window_start, window_end) if window: if not station_match: station_windows = { 'id': station.id, 'name': station.name, 'window': [] } station_match = True window_start = window[0] window_end = window[1] station_windows['window'].append( { 'start': window_start.strftime("%Y-%m-%d %H:%M:%S.%f"), 'end': window_end.strftime("%Y-%m-%d %H:%M:%S.%f"), 'az_start': azr }) # In case our window was split in two try: window_start = window[2] window_end = window[3] station_windows['window'].append( { 'start': window_start.strftime("%Y-%m-%d %H:%M:%S.%f"), 'end': window_end.strftime("%Y-%m-%d %H:%M:%S.%f"), 'az_start': azr }) except IndexError: pass else: # window start outside of window bounds break else: # did not rise above user configured horizon break if station_match: data.append(station_windows) return JsonResponse(data, safe=False)
def get_nearest_time(self, line1, line2, year, month, day): # Get TLE record tle_rec = ephem.readtle(self.name, line1, line2) # Start with day boundary # First work out if ascending or not time = datetime.datetime(year, month, day) time_add_day = time + datetime.timedelta(seconds=86400) # Now get times of equator crossing - depends on satellite for daytime case (needed for solar contamination) ascending = self.get_ascending_descending_type() # Now Loop round a complete day to get times of equator crossing # including first one in next day ok = False i = 0 time_arr = [] while True: intime = time + datetime.timedelta(seconds=i * 60) if intime >= time_add_day: break tle_rec.compute(intime) if 0 == i: start_lat = tle_rec.sublat else: if ascending: if tle_rec.sublat >= 0. and start_lat <= 0.: ok = True time_arr.append(intime) else: if tle_rec.sublat <= 0. and start_lat >= 0.: ok = True time_arr.append(intime) start_lat = tle_rec.sublat i = i + 1 # Get first cross over day boundary ok = False i = 0 while True: intime = time_add_day + datetime.timedelta(seconds=i * 60) tle_rec.compute(intime) if 0 == i: start_lat = tle_rec.sublat else: if not ascending: if tle_rec.sublat >= 0. and start_lat <= 0.: ok = True time_arr.append(intime) break else: if tle_rec.sublat <= 0. and start_lat >= 0.: ok = True time_arr.append(intime) break start_lat = tle_rec.sublat i = i + 1 if not ok: raise Exception("ERROR: Cannot find equator from TLE") return time_arr
def __init__(self, name, line_1, line_2): self.ep = ephem.readtle(name, line_1, line_2) self.vlist = satel_vlist self.label = pyglet.text.Label(self.ep.name, y=15, anchor_x="center", color=(255,255,255,200)) self.compute()
def parse(name, line1, line2): tle_rec = ephem.readtle(name, line1, line2) tle_rec.compute() return tle_rec
import math import time from datetime import datetime import ephem import sys import urllib.request NORAD = urllib.request.urlopen( 'https://www.celestrak.com/NORAD/elements/stations.txt') with open('norad.txt', 'w+b') as f: f.write(NORAD.read()) degrees_per_radian = 180.0 / math.pi home = ephem.Observer() home.lon = sys.argv[1] # +E home.lat = sys.argv[2] # +N home.elevation = int(sys.argv[3]) # meters iss = ephem.readtle( 'ISS', '1 25544U 98067A 16053.61773880 .00007242 00000-0 11608-3 0 9999', '2 25544 51.6425 274.3549 0004199 154.0845 254.2150 15.54236294987003') while True: home.date = datetime.utcnow() iss.compute(home) print('iss: altitude %4.2f deg, azimuth %5.2f deg' % (iss.alt * degrees_per_radian, iss.az * degrees_per_radian)) time.sleep(.5)