Beispiel #1
0
 def test_63(self):
     """Check that no runtimewarning is raised, #63."""
     import warnings
     from pyorbital.orbital import Orbital
     from dateutil import parser
     warnings.filterwarnings('error')
     orb = Orbital("Suomi-NPP",
                   line1="1 37849U 11061A   19292.84582509  .00000011  00000-0  25668-4 0  9997",
                   line2="2 37849  98.7092 229.3263 0000715  98.5313 290.6262 14.19554485413345")
     orb.get_next_passes(parser.parse("2019-10-21 16:00:00"), 12, 123.29736, -13.93763, 0)
     warnings.filterwarnings('default')
def time_above_the_horizon(ground_position_lat, ground_position_lon, date, date_format = "%d/%m/%Y", time_window = 24, satellite_sensor = 'aqua', elevation = 0):
    '''time_above_the_horizon calculates the observation times of satellite passes for the day and time window of a given position on the earth.
    It is based on pyorbital functions.

    ground_position_lat = -19.2590 # The latitude of the ground position (int)
    ground_position_lon = 146.8169 # The longitude of the ground position (int)
    date = '21/06/2016' # date of the day to find passes on. (This is techincally in local time for your location an is converted to UTC internally here.) (string)
    date_format = "%d/%m/%Y" # the format of thh date string (string)
    satellite_sensor = 'aqua' # the name of the satellite sensor you are tracking (string). for VIIRS use 'SUOMI NPP'
    time_window = 24 # Number of hours to find passes (int)
    elevation = 0 # the elevation of horizon to compute risetime and falltime. (int)

    Returns: [(rise-time, fall-time, max-elevation-time), ...] as datetime objects in the UTC time zone.

    Contact:
    [email protected]
    '''
    # check the lat and lons to be sensible.
    futs.check_for_sensible_lat_long([ground_position_lat, ground_position_lon])
    #set up the satellite
    orb = Orbital(satellite_sensor)
    # convert the local time to a utc time.
    utc_date = futs.local_to_utc(futs.which_time_zone(ground_position_lat, ground_position_lon), date, date_format)
    # do calcs and remove the utc awareness from the utc_date so that pyorbital can use it.
    time_satellite_is_above_horizon = orb.get_next_passes(utc_date.replace(tzinfo=None), time_window, ground_position_lon, ground_position_lon, elevation)
    return time_satellite_is_above_horizon
Beispiel #3
0
def predict_next_passes(tle_dir: str, satellites: dict, station_location: dict,
                        min_elevation: float, for_next_hours: int) -> list:
    all_passes = []
    time_now_utc = datetime.datetime.utcnow()

    for sat_name in satellites:
        sat = satellites[sat_name]
        sat_type = sat["type"]

        orbital = Orbital(sat_name,
                          tle_file="{}/{}/{}.tle".format(
                              tle_dir, sat_type, sat_name))
        passes = orbital.get_next_passes(time_now_utc +
                                         datetime.timedelta(seconds=-60 * 20),
                                         for_next_hours,
                                         station_location["lon"],
                                         station_location["lat"],
                                         station_location["alt"],
                                         horizon=min_elevation)

        all_passes += [{
            "type": sat_type,
            "name": sat_name,
            "rise_time": pas[0],
            "fall_time": pas[1],
            "duration": (pas[1] - pas[0]).total_seconds()
        } for pas in passes]
    all_passes.sort(key=lambda t: t["rise_time"])

    return all_passes
Beispiel #4
0
def serialPortRead(passNumber):
    #passes = satOrb.get_next_passes(datetime.utcnow(),120, -30.8047389406, 72.9167, 180.85)
    
    #next get number of passes the user wants  
    satOrb = Orbital(satName, tleFile)
    passes = satOrb.get_next_passes(current_time,int(passNumber), home.lat, home.lon, home.elevation)
    for eachPass in passes:
                rise = eachPass[0]
                fall = eachPass[1]
                apex = eachPass[2]
                
                # Lon, Lat
                obsRiseAngle, obsRiseElv = satOrb.get_observer_look(rise, home.lat, home.lon, home.elevation)
                obsFallAngle, obsFallElv = satOrb.get_observer_look(fall, home.lat, home.lon, home.elevation)
                obsApexAngle, obsApexElv = satOrb.get_observer_look(apex, home.lat, home.lon, home.elevation)
                print("observer apex", obsApexElv)
                print("Rise Time:", rise, "Azimuth:", round(obsRiseAngle, 2), 
                          '(', azimuthDirection(obsRiseAngle), ')', "Elevation:", abs(round(obsRiseElv, 2)))
                    
                print("Apex Time:", apex, "Azimuth:", round(obsApexAngle, 2),
                          '(', azimuthDirection(obsApexAngle), ')', "Elevation:", abs(round(obsApexElv, 2)))
                          
                print("Fall Time:", fall, "Azimuth:", round(obsFallAngle, 2), 
                          '(', azimuthDirection(obsFallAngle), ')', "Elevation:", abs(round(obsFallElv, 2)))
                print()
                return
Beispiel #5
0
def runProp():
    #orb = Orbital(tle)
    orb = Orbital("TJREVERB", tle_file="FILE PATH TO TLE")
    now = datetime.utcnow()
    #print(tle.inclination)
    #print(orb.get_position(now))
    print(orb.get_lonlatalt(now))
    print()
    print(orb.get_next_passes(now, 12, -77.10428, 8.88101, 276, tol=0.001, horizon=0))
def getSentinel2Geometry(startDateUTC, lengthDays, lat, lon, alt=0.0, mission="Sentinel-2a",
                         tleFile="../TLE/norad_resource_tle.txt"):
    """Calculate approximate geometry for Sentinel overpasses.
    Approximate because it assumes maximum satellite elevation
    is the time at which target is imaged.

    :param startDateUTC: a datetime object specifying when to start prediction.
    :type startDateUTC: object
    :param lengthDays: number of days over which to perform calculations.
    :type lengthDays: int
    :param lat: latitude of target.
    :type lat: float
    :param lon: longitude of target.
    :type lon: float
    :param alt: altitude of target (in km).
    :type alt: float
    :param mission: mission name as in TLE file.
    :type mission: str
    :param tleFile: TLE file.
    :type tleFile: str
    :return: a python list containing instances of the sensorGeometry class arranged in date order.
    :rtype: list
    """
    orb = Orbital(mission, tleFile)
    passes = orb.get_next_passes(startDateUTC, 24 * lengthDays, lon, lat, alt)

    geomList = []

    for p in passes:
        look = orb.get_observer_look(p[2], lon, lat, alt)
        vza = 90 - look[1]
        vaa = look[0]
        sza = ast.sun_zenith_angle(p[2], lon, lat)
        saa = np.rad2deg(ast.get_alt_az(p[2], lon, lat)[1])

        if sza < 90 and vza < 10.3:
            thisGeom = sensorGeometry()
            thisGeom.date_utc = p[2]
            thisGeom.vza = vza
            thisGeom.vaa = vaa
            thisGeom.sza = sza
            thisGeom.saa = saa
            geomList.append(thisGeom)

    return geomList
Beispiel #7
0
def get_passes():
    now = datetime.utcnow()  # get current time UTC
    next_pass_delta = 0  # time until next pass
    sat_name_temp = ""  # temporary variable to return

    for i in range(
            0, len(sats_name)
    ):  # loop through the number of satellites in the configuration file

        try:
            current_sat = Orbital(
                sats_name[i], tle_file=path_to_tle
            )  # set current satellite and check it's in the TLE
            # file
        except:  # sue me
            print(
                "Error loading TLE data for {}. Check TLE file is present and the satellite name is correct and inclu"
                "ded in the TEL file with correct elements".format(
                    sats_name[i]))  # something went wrong
            continue

        # calculate all passes within the search time
        passes = current_sat.get_next_passes(now,
                                             search_time,
                                             lon,
                                             lat,
                                             alt,
                                             tol=1,
                                             horizon=horizon)

        if len(passes
               ) != 0:  # if the satellite will pass within the search time
            sat_pass = passes[0][0]  # get earliest pass
            pass_timedelta = sat_pass - now  # get time until next pass of satellite
            seconds_until_pass = pass_timedelta.total_seconds(
            )  # convert timedelta to seconds until next pass

            if seconds_until_pass <= next_pass_delta or next_pass_delta == 0:  # if this pass is the earliest so far
                next_pass_delta = seconds_until_pass  # set next_pass_delta to delta of earliest pass
                sat_name_temp = sats_name[
                    i]  # record earliest pass satellite name
    return sat_name_temp  # return name of next pass
Beispiel #8
0
def calculate_pass_info(
    name
):  # calculates times of next pass and creates a Satellite object to store them
    now = datetime.utcnow()
    current_sat = Orbital(name, tle_file=path_to_tle)
    passes = current_sat.get_next_passes(now,
                                         search_time,
                                         lon,
                                         lat,
                                         alt,
                                         tol=1,
                                         horizon=horizon)
    sat_pass = passes[0][0]
    pass_timedelta = sat_pass - now
    seconds_until = pass_timedelta.total_seconds()
    passduration = int((passes[0][1] - passes[0][0]).total_seconds())
    sat = Satellite(name, passes[0][0], passes[0][2], passes[0][1],
                    seconds_until, passduration,
                    sats_freq[sats_name.index(name)])
    return sat  # returns sat object
Beispiel #9
0
from pyorbital.orbital import Orbital
from datetime import datetime

# 国際宇宙ステーション
orb = Orbital("ISS (ZARYA)") 

# 福岡市役所
(lat, lon, alt) =  (33.590198, 130.401719, 4.0) 

# 現在時刻(UTC): 2019-07-07 11:24:46
now = datetime.utcnow() 

# 福岡市役所からみて24時間以内の観測可能な時間
passTimes = orb.get_next_passes(now, 24, lon, lat, alt, tol=0.001, horizon=0)

print("福岡市役所の次のPassの時間は(UTC): ", passTimes[0][0].strftime('%Y-%m-%d %H:%M:%S'))
#=> 福岡市役所の次のPassの時間は(UTC):  2019-07-07 14:16:35



Beispiel #10
0
database = db("main", autoOpenClose=False)
database.open()

for sh in database.activeScheduleList():

    sat = database.satellite(sh['satelliteId'])
    pyOrbital = Orbital(sat["tle1"], line1=sat["tle2"], line2=sat["tle3"])

    utctime = datetime.utcnow()

    gr = sh['groundStation']

    passes = pyOrbital.get_next_passes(utctime,
                                       24,
                                       setting.groundStations[gr]["lon"],
                                       setting.groundStations[gr]["lat"],
                                       setting.groundStations[gr]["alt"],
                                       tol=0.001)

    if len(passes) > 0:
        print("[INFO] new pass for satellite %s - %s" %
              (sh['id'], passes[0][0].strftime("%m/%d/%Y, %H:%M:%S")))
        database.updateSchedulePass(sh['id'], passes[0])

    else:
        print("[INFO] no new pass for satellite %s" % (sh['id']))
        database.clearSchedulePass(sh['id'])

database.close()
def SatStats():
    
    #tle = r"C:\Users\Jake\Python\TLE Files\stations-tle.txt"
    
    # Download TLE file
    #downloadUrl = "http://www.celestrak.com/NORAD/elements/stations.txt"
    #urllib.request.urlretrieve(downloadUrl, tle)

    tle = GetTLEFile()
    
    stationList = GetStationList(tle)
    
        
    try:
        while(True):
            stationNumber = input("Enter Station Number: ")
            print()
            
            if stationNumber == 'n':
                for name in enumerate(stationList):
                    print(name[0], ':', name[1].replace('\n', ''))
                
                print()
                    
            else:
                break
    
        stationNumber = int(stationNumber)
        
        if stationNumber < len(stationList):
            # Get Platform Object
        
            station = stationList[stationNumber]
            stationObject = tlefile.read(station, tle)
                    
            GoogleSearch(station)

            # Print Platform Info
            PrintTLEInfo(stationObject, station)
            
            lon, lat, alt, now = GetGPSPosition(station, tle, datetime.utcnow())                    
            dmLon, dmLat = DegreeMinutes(lon, lat)
                    
            print("Current GPS location:\n", "Latitude: ", lat, " Longitude: ", lon, " Altitude (km): ", alt, sep='')
            print("Current GPS location:\n", "Latitude: ", dmLat, " Longitude: ", dmLon, " Altitude (km): ", alt, sep='')
            satOrb = Orbital(station, tle)
            
            print()
        
            PrintFreqData(GetFreqData(station, "C:/Users/Jake/Python/Satellite Tracker/frequencies/satfreqlist.csv"))
            
            
            passes = satOrb.get_next_passes(datetime.utcnow(), 120, -90.5546910, 38.6475290, 180.85)
            
            
            print("Next passes in 5 days (Max Elevation Above 20 deg):")
            
            for eachPass in passes:
                rise = eachPass[0]
                fall = eachPass[1]
                apex = eachPass[2]
                
                # Lon, Lat
                obsRiseAngle, obsRiseElv = satOrb.get_observer_look(rise, -90.5546910, 38.6475290, 180.85)
                obsFallAngle, obsFallElv = satOrb.get_observer_look(fall, -90.5546910, 38.6475290, 180.85)
                obsApexAngle, obsApexElv = satOrb.get_observer_look(apex, -90.5546910, 38.6475290, 180.85)
                
                if obsApexElv >= 20.0:
                    print("Rise Time:", rise, "Azimuth:", round(obsRiseAngle, 2), 
                          '(', AzimuthDirection(obsRiseAngle), ')', "Elevation:", abs(round(obsRiseElv, 2)))
                    
                    print("Apex Time:", apex, "Azimuth:", round(obsApexAngle, 2),
                          '(', AzimuthDirection(obsApexAngle), ')', "Elevation:", abs(round(obsApexElv, 2)))
                          
                    print("Fall Time:", fall, "Azimuth:", round(obsFallAngle, 2), 
                          '(', AzimuthDirection(obsFallAngle), ')', "Elevation:", abs(round(obsFallElv, 2)))
                    print()
    except: 
        pass    
Beispiel #12
0
def trackHotspotSatellite(arglist=None):

    parser = ArgumentRecorder(
        description=
        'Track satellite position, bearing, previous and next passdatetimes from hotspot data.',
        fromfile_prefix_chars='@')

    parser.add_argument('-v', '--verbosity', type=int, default=1, private=True)

    parser.add_argument('-u',
                        '--user',
                        type=str,
                        required=True,
                        help="PostgreSQL username")
    parser.add_argument('-d',
                        '--database',
                        type=str,
                        required=True,
                        help="PostgreSQL database")

    parser.add_argument('-l',
                        '--limit',
                        type=int,
                        help='Limit number of rows to process')

    parser.add_argument('-t',
                        '--tlefile',
                        type=str,
                        required=True,
                        help='File containing TLE data')
    parser.add_argument('-w',
                        '--where',
                        type=str,
                        required=True,
                        help="'Where' clause to select hotspots")
    parser.add_argument('-H',
                        '--hotspots',
                        type=str,
                        default='hotspots',
                        help="Hotspot table name")
    parser.add_argument(
        '-s',
        '--suffix',
        type=str,
        required=True,
        help="Suffix to append to 'hotspots' to get output table name")
    parser.add_argument('-D',
                        '--drop-table',
                        action='store_true',
                        help='Drop output table if it exists')

    parser.add_argument('--logfile',
                        type=str,
                        help="Logfile, default is 'hotspots'_'suffix'.log",
                        private=True)
    parser.add_argument('--no-logfile',
                        action='store_true',
                        help='Do not output descriptive comments')

    args = parser.parse_args(arglist)

    if not args.no_logfile:
        if not args.logfile:
            args.logfile = args.hotspots + '_' + args.suffix + '.log'

        if os.path.exists(args.logfile):
            shutil.move(args.logfile,
                        args.logfile.split('/')[-1].rsplit('.', 1)[0] + '.bak')

        logfile = open(args.logfile, 'w')
        parser.write_comments(args,
                              logfile,
                              incomments=ArgumentHelper.separator())
        logfile.close()

    satcodes = {'N': 37849, 'Terra': 25994, 'Aqua': 27424}

    tledict = {}
    for norad_id in satcodes.values():
        tledict[norad_id] = ()

    tlefile = open(args.tlefile, 'r')
    line1 = tlefile.readline().rstrip()
    while len(line1) > 1:
        norad_id = int(line1[2:7])
        year2d = int(line1[18:20])
        daynum = float(line1[20:32])
        tledate = datetime(2000 + year2d if year2d <= 56 else 1900 + year2d, 1,
                           1) + timedelta(days=daynum)
        line2 = tlefile.readline().rstrip()
        tledict[norad_id] += ((tledate, line1, line2), )
        line1 = tlefile.readline().rstrip()

    psqlin = subprocess.Popen([
        'psql', args.database, args.user, '--quiet', '--command',
        r'\timing off', '--command',
        r'\copy (SELECT * FROM ' + args.hotspots + ' WHERE ' + args.where +
        ' ORDER BY acq_date + acq_time) TO STDOUT CSV HEADER'
    ],
                              stdout=subprocess.PIPE,
                              encoding='UTF-8')

    satcsv = csv.DictReader(psqlin.stdout)

    psqlout = subprocess.Popen([
        'psql', args.database, args.user, '--quiet', '--command',
        r'\timing off'
    ] + ([
        '--command', 'DROP TABLE IF EXISTS ' + args.hotspots + '_' +
        args.suffix
    ] if args.drop_table else []) + [
        '--command', 'CREATE TABLE ' + args.hotspots + '_' + args.suffix +
        ' AS TABLE ' + args.hotspots + ' WITH NO DATA', '--command',
        'ALTER TABLE ' + args.hotspots + '_' + args.suffix + '     \
                                                  ADD COLUMN pass_azimuth NUMERIC(8,5),                 \
                                                  ADD COLUMN pass_elevation NUMERIC(8,5),               \
                                                  ADD COLUMN pass_bearing NUMERIC(8,5),                 \
                                                  ADD COLUMN pass_datetime TIMESTAMP WITHOUT TIME ZONE, \
                                                  ADD COLUMN prev_azimuth NUMERIC(8,5),                 \
                                                  ADD COLUMN prev_elevation NUMERIC(8,5),               \
                                                  ADD COLUMN prev_datetime TIMESTAMP WITHOUT TIME ZONE, \
                                                  ADD COLUMN next_azimuth NUMERIC(8,5),                 \
                                                  ADD COLUMN next_elevation NUMERIC(8,5),               \
                                                  ADD COLUMN next_datetime TIMESTAMP WITHOUT TIME ZONE, \
                                                  DROP COLUMN IF EXISTS geometry,                       \
                                                  ADD COLUMN geometry geometry GENERATED ALWAYS AS (ST_Rotate(ST_MakeEnvelope((ST_X(ST_Transform(ST_SetSRID(ST_MakePoint((longitude)::DOUBLE PRECISION, (latitude)::DOUBLE PRECISION), 4326), 28350)) - ((scan * (500)::NUMERIC))::DOUBLE PRECISION), (ST_Y(ST_Transform(ST_SetSRID(ST_MakePoint((longitude)::DOUBLE PRECISION, (latitude)::DOUBLE PRECISION), 4326), 28350)) - ((track * (500)::NUMERIC))::DOUBLE PRECISION), (ST_X(ST_Transform(ST_SetSRID(ST_MakePoint((longitude)::DOUBLE PRECISION, (latitude)::DOUBLE PRECISION), 4326), 28350)) + ((scan * (500)::NUMERIC))::DOUBLE PRECISION), (ST_Y(ST_Transform(ST_SetSRID(ST_MakePoint((longitude)::DOUBLE PRECISION, (latitude)::DOUBLE PRECISION), 4326), 28350)) + ((track * (500)::NUMERIC))::DOUBLE PRECISION), 28350), ((((- pass_bearing) * 3.1415926) / (180)::NUMERIC))::DOUBLE PRECISION, ST_Transform(ST_SetSRID(ST_MakePoint((longitude)::DOUBLE PRECISION, (latitude)::DOUBLE PRECISION), 4326), 28350))) STORED',
        '--command', r'\copy ' + args.hotspots + '_' + args.suffix +
        ' FROM STDIN CSV HEADER', '--command',
        'ALTER TABLE ' + args.hotspots + '_' + args.suffix + '     \
                                                  ADD COLUMN id SERIAL'
    ],
                               stdin=subprocess.PIPE,
                               encoding='UTF-8')

    satout = csv.DictWriter(
        psqlout.stdin,
        fieldnames=satcsv.fieldnames + [
            'pass_azimuth', 'pass_elevation', 'pass_bearing', 'pass_datetime',
            'prev_azimuth', 'prev_elevation', 'prev_datetime', 'next_azimuth',
            'next_elevation', 'next_datetime'
        ])

    minelevation = 90
    tleindexes = {}
    lastdatetime = datetime(MINYEAR, 1, 1)
    lastline1 = None
    lastline2 = None
    inrowcount = 0
    for satline in satcsv:
        thisdatetime = dateparser.parse(satline['acq_date'] + ' ' +
                                        satline['acq_time'])
        satcode = satcodes[satline['satellite']]
        tletuples = tledict[satcode]
        tleidx = tleindexes.get(satcode, 0)
        assert (thisdatetime >= lastdatetime)
        lastdatetime = thisdatetime
        while tletuples[tleidx + 1][0] <= thisdatetime - timedelta(hours=12):
            tleidx += 1
        tleindexes[satcode] = tleidx

        tletuple = tletuples[tleidx]
        line1 = tletuple[1]
        line2 = tletuple[2]

        if line1 != lastline1 or line2 != lastline2:
            orb = Orbital("", line1=line1, line2=line2)
            lastline1 = line1
            lastline2 = line2

        passdatetimes = [
            next_pass[2]
            for next_pass in orb.get_next_passes(thisdatetime -
                                                 timedelta(hours=24),
                                                 48,
                                                 float(satline['longitude']),
                                                 float(satline['latitude']),
                                                 0,
                                                 horizon=0)
        ]

        nearpasses = []
        leastoffset = 999999
        leastoffsetidx = None
        for passidx in range(len(passdatetimes)):
            max_elevation_time = passdatetimes[passidx]
            (azimuth,
             elevation) = orb.get_observer_look(max_elevation_time,
                                                float(satline['longitude']),
                                                float(satline['latitude']), 0)
            thisoffset = (max_elevation_time - thisdatetime).total_seconds()
            if abs(thisoffset) < abs(leastoffset):
                leastoffsetidx = len(nearpasses)
                leastoffset = thisoffset

            nearpasses += [(max_elevation_time, azimuth, elevation)]

        if abs(leastoffset) > 600:
            print("WARNING: offset=", leastoffset, "prev offset=",
                  (nearpasses[leastoffsetidx - 1][0] -
                   thisdatetime).total_seconds() if leastoffsetidx > 0 else "",
                  "next offset=", (nearpasses[leastoffsetidx + 1][0] -
                                   thisdatetime).total_seconds()
                  if leastoffsetidx < len(nearpasses) - 1 else "",
                  " satellite ", satline['satellite'])
            #print("   ", satline)

        if len(nearpasses):
            nearestpass = nearpasses[leastoffsetidx]
            satline['pass_datetime'] = nearestpass[0]
            satline['pass_azimuth'] = nearestpass[1]
            satline['pass_elevation'] = nearestpass[2]

            (lon1, lat1, alt1) = orb.get_lonlatalt(max_elevation_time -
                                                   timedelta(seconds=30))
            (lon2, lat2, alt2) = orb.get_lonlatalt(max_elevation_time +
                                                   timedelta(seconds=30))
            point1 = (lon1, lat1)
            point2 = (lon2, lat2)
            bearing = sphere.bearing(point1, point2)
            satline['pass_bearing'] = bearing

            if leastoffsetidx > 0:
                prevpass = nearpasses[leastoffsetidx - 1]
                satline['prev_datetime'] = prevpass[0]
                satline['prev_azimuth'] = prevpass[1]
                satline['prev_elevation'] = prevpass[2]

            if leastoffsetidx < len(nearpasses) - 1:
                nextpass = nearpasses[leastoffsetidx + 1]
                satline['next_datetime'] = nextpass[0]
                satline['next_azimuth'] = nextpass[1]
                satline['next_elevation'] = nextpass[2]

        satout.writerow(satline)

        inrowcount += 1
        if args.limit and inrowcount == args.limit:
            break
def get_satellite_geometry(startDateUTC,
                           lengthDays,
                           lon,
                           lat,
                           alt=0.0,
                           mission="Sentinel-2a",
                           tleFile="/data/tle/norad_resource_tle.txt"):
    """Calculate approximate geometry for Sentinel overpasses.
    Approximate because it assumes maximum satellite elevation
    is the time at which target is imaged.

    :param startDateUTC: a datetime object specifying when to start prediction.
    :type startDateUTC: object
    :param lengthDays: number of days over which to perform calculations.
    :type lengthDays: int
    :param lat: latitude of target.
    :type lat: float
    :param lon: longitude of target.
    :type lon: float
    :param alt: altitude of target (in km).
    :type alt: float
    :param mission: mission name as in TLE file.
    :type mission: str
    :param tleFile: TLE file.
    :type tleFile: str
    :return: a python list containing instances of the sensorGeometry class arranged in date order.
    :rtype: list
    """
    orb = Orbital(mission, tleFile)
    passes = orb.get_next_passes(startDateUTC, 24 * lengthDays, lon, lat, alt)

    geom_inst = SensorGeometry()
    geom_inst.date_utc = []
    geom_inst.vza = []
    geom_inst.vaa = []
    geom_inst.sza = []
    geom_inst.saa = []

    for p in passes:
        look = orb.get_observer_look(p[2], lon, lat, alt)
        vza = 90 - look[1]
        vaa = look[0]
        sza = ast.sun_zenith_angle(p[2], lon, lat)
        saa = np.rad2deg(ast.get_alt_az(p[2], lon, lat)[1])

        if mission == 'Sentinel-1b':
            if 75 < vaa < 105 and 20. < vza < 45.:  # vaa usually [0, 180], testing observation times
                geom_inst.date_utc.append(p[2])
                geom_inst.vza.append(vza)
                geom_inst.vaa.append(vaa)
                geom_inst.sza.append(sza)
                geom_inst.saa.append(saa)
        elif mission == 'Sentinel-1a':
            if 75 < vaa < 105 and 20. < vza < 45.:  # vaa usually [0, 180], testing observation times
                geom_inst.date_utc.append(p[2])
                geom_inst.vza.append(vza)
                geom_inst.vaa.append(vaa)
                geom_inst.sza.append(sza)
                geom_inst.saa.append(saa)
        elif mission == 'Sentinel-2a':
            if sza < 90 and vza < 10.3:
                geom_inst.date_utc.append(p[2])
                geom_inst.vza.append(vza)
                geom_inst.vaa.append(vaa)
                geom_inst.sza.append(sza)
                geom_inst.saa.append(saa)

    return geom_inst
Beispiel #14
0
#now = datetime.datetime.utcnow()
now = t = datetime.datetime(2020, 3, 1, 0, 0, 0, 0, datetime.timezone.utc)

# 現在の緯度、経度、高度を取得
lon, lat, alt = aqua_orbit.get_lonlatalt(now)
print('Aquaの現在地')
print('経度: ', lon)
print('緯度: ', lat)
print('高度[km]: ', alt)
print('')

# 24時間以内に東京タワーから衛星が見える時間を計算
pass_time_list = (aqua_orbit.get_next_passes(utc_time=now,
                                             length=24,
                                             lon=139.75,
                                             lat=35.66,
                                             alt=0.333))
print('次にAquaが到来する時刻[UTC]: ',
      pass_time_list[0][0].strftime('%Y/%m/%d %H:%M:%S'))

#exit()

#beginDate = datetime.datetime(2020, 1, 1, 9, 0, 0, 0, datetime.timezone(datetime.timedelta(hours=+9))).astimezone(datetime.timezone.utc)
beginDate = datetime.datetime.now(datetime.timezone.utc)
endDate = beginDate + datetime.timedelta(days=16)
pointNum = 10000
period = endDate - beginDate
step = period / pointNum
#logger.info('beginDate = {}, endDate = {}, period = {}, step = {}'.format(beginDate, endDate, period, step))
Beispiel #15
0
import argparse

# altitude (km) above seal-level and lat lon of the observer
TLE_FILE_NAME = 'cubesat.txt'
ALTITUDE_ASL = 0
LAT = 64.146
LONG = 21.942

passhour = 0

while passhour < 24:
    # set the date with a variable for the hour
    d = datetime(2020, 5, 9, passhour, 0, 0)
    orb = Orbital('CUBESAT', 'cubesat.txt')
    # generate pass information for the hour specified
    passes = orb.get_next_passes(d, 1, LONG, LAT, ALTITUDE_ASL, horizon=1)
    # if there is no pass for the current value of passhour, the length will be zero
    if len(passes) > 0:
        rise_az, rise_el = orb.get_observer_look(passes[0][0], LONG, LAT,
                                                 ALTITUDE_ASL)
        transit_az, transit_el = orb.get_observer_look(passes[0][2], LONG, LAT,
                                                       ALTITUDE_ASL)
        set_az, set_el = orb.get_observer_look(passes[0][1], LONG, LAT,
                                               ALTITUDE_ASL)

        # print out the pass info
        print("CUBESAT")
        print(passes[0][0], rise_az, rise_el)
        print(passes[0][2], transit_az, transit_el)
        print(passes[0][1], set_az, set_el)
        print()
Beispiel #16
0
def get_site_passes(
    satno, site, duration, filename
):  # Duration in hours from current time,  # filename = file with TLEs in it

    now = datetime.utcnow()  # set time to current time
    sat = Orbital(satellite='None',
                  line1=getTLE(satno, filename)[0],
                  line2=getTLE(satno, filename)[1])
    x = Orbital.get_next_passes(
        sat,
        now,
        duration,
        site[1],
        site[0],
        site[2],
        tol=0.001,
        horizon=site[3])  # builds list of all passes that break 3 degrees
    passes = []  # begins empty list for passes
    for i in x:
        en = Orbital.get_observer_look(sat, i[0], site[1], site[0],
                                       site[2])  # Gets entry Az & El
        ex = Orbital.get_observer_look(sat, i[1], site[1], site[0],
                                       site[2])  # Gets exitAz & El
        hi = Orbital.get_observer_look(sat, i[2], site[1], site[0],
                                       site[2])  # Gets exitAz & El
        p1 = Orbital.get_observer_look(sat, i[0], site[1], site[0],
                                       site[2])[0]  # az at 3 degree entry
        p2 = Orbital.get_observer_look(sat, i[0] + timedelta(seconds=1),
                                       site[1], site[0],
                                       site[2])[0]  # p1 1 seconds later
        p3 = Orbital.get_observer_look(sat, i[1], site[1], site[0],
                                       site[2])[0]  # az at 3 degree exit

        print(site[8], "Pass Start:", i[0], "Enter Az", en[0], "Pass Term:",
              i[1], "Exit Az:", ex[0], "MaxEl:",
              hi[1])  # prints passes (used for dev)

        if site[4] < en[0] < site[5] or site[6] < en[0] < site[
                7]:  # if satellite enters FOV on face *checkpass*
            len = int(
                (i[1] - i[0]).total_seconds())  # length of pass in seconds
            passes.append(
                i[0]
            )  # appedns check passes to passes list            print("Check Pass | Az:", en[0])  # prints pass info (used for dev)

        elif not site[4] < en[0] < site[5]:  # if enters FOV not on face1
            print("Fence Pass | Az:", ex[0])  # prints pass info (used for dev)

            if (p1 - p2) < 0:  # if the azimuth is growing after 5 seconds
                rx = i[
                    0]  # Sets variables so it doesn't mess up other operations
                while p1 <= site[
                        6]:  # looks for when azimuth breaches sides of coverage
                    p1 = Orbital.get_observer_look(
                        sat, rx, site[1], site[0],
                        site[2])[0]  # gets new azimuth
                    rx = rx + timedelta(
                        seconds=10
                    )  # sets time for 10s later to retrieve azimuth at that time
                print("Fence Time:", rx, "Angle:",
                      p1)  # prints pass info (used for dev)
                len = int((i[1] - rx).total_seconds())
                passes.append(rx)

            if (p1 - p2) > 0:  # if the azimuth is shrinking after 5 seconds
                rx = i[
                    0]  # Sets variables so it doesn't mess up other operations
                while p1 >= site[
                        6]:  # looks for when azimuth breaches sides of coverage
                    p1 = Orbital.get_observer_look(
                        sat, rx, site[1], site[0],
                        site[2])[0]  # gets new azimuth
                    rx = rx + timedelta(seconds=10)
                print("Fence Time:", rx, "Angle:",
                      p1)  # prints passe info (used for dev)
                len = int((i[1] - rx).total_seconds())
                passes.append(rx)  # appedns check passes to passes list

        elif not site[6] < en[0] < site[7]:  # if enters FOV not on face2
            print("Fence Pass | Az:", ex[0])  # prints pass info (used for dev)

            if (p1 - p2) < 0:  # if the azimuth is growing after 5 seconds
                rx = i[
                    0]  # Sets variables so it doesn't mess up other operations
                while p1 <= site[
                        6]:  # looks for when azimuth breaches sides of coverage
                    p1 = Orbital.get_observer_look(
                        sat, rx, site[1], site[0],
                        site[2])[0]  # gets new azimuth
                    rx = rx + timedelta(
                        seconds=10
                    )  # sets time for 10s later to retrieve azimuth at that time
                print("Fence Time:", rx, "Angle:",
                      p1)  # prints pass info (used for dev)
                len = int((i[1] - rx).total_seconds())

                passes.append(rx)  # appedns check passes to passes list

            if (p1 - p2) > 0:  # if the azimuth is shrinking after 5 seconds
                rx = i[
                    0]  # Sets variables so it doesn't mess up other operations
                while p1 >= site[
                        6]:  # looks for when azimuth breaches sides of coverage
                    p1 = Orbital.get_observer_look(
                        sat, rx, site[1], site[0],
                        site[2])[0]  # gets new azimuth
                    rx = rx + timedelta(
                        seconds=10
                    )  # sets time for 10s later to retrieve azimuth at that time
                print("Fence Time:", rx, "Angle:",
                      p1)  # prints pass info (used for dev)
                len = int((i[1] - rx).total_seconds())

                passes.append(rx)  # appedns check passes to passes list

        if len < 0:
            print("Not a Pass")
        elif len < 180:
            print("Pass Length: ", len, "sec (short)")
        else:
            print("Pass Length: ", len, "sec")
    return passes  # Returns datetime objects for all passes
Beispiel #17
0
def can_TJ_be_seen(t):
  orb = Orbital("TJREVERB", tle_file=(
        Path(__file__).parent.resolve() / "tjreverb_tle.txt"))
  a=orb.get_next_passes(t, 1, -77.1687977, 38.8183519, .08, tol=0.001, horizon=0)
  return(a[0][0]<=t and t<=a[0][1])
def SatStats():

    #tle = r"C:\Users\Jake\Python\TLE Files\stations-tle.txt"

    # Download TLE file
    #downloadUrl = "http://www.celestrak.com/NORAD/elements/stations.txt"
    #urllib.request.urlretrieve(downloadUrl, tle)

    tle = GetTLEFile()

    stationList = GetStationList(tle)

    try:
        while (True):
            stationNumber = input("Enter Station Number: ")
            print()

            if stationNumber == 'n':
                for name in enumerate(stationList):
                    print(name[0], ':', name[1].replace('\n', ''))

                print()

            else:
                break

        stationNumber = int(stationNumber)

        if stationNumber < len(stationList):
            # Get Platform Object

            station = stationList[stationNumber]
            stationObject = tlefile.read(station, tle)

            GoogleSearch(station)

            # Print Platform Info
            PrintTLEInfo(stationObject, station)

            lon, lat, alt, now = GetGPSPosition(station, tle,
                                                datetime.utcnow())
            dmLon, dmLat = DegreeMinutes(lon, lat)

            print("Current GPS location:\n",
                  "Latitude: ",
                  lat,
                  " Longitude: ",
                  lon,
                  " Altitude (km): ",
                  alt,
                  sep='')
            print("Current GPS location:\n",
                  "Latitude: ",
                  dmLat,
                  " Longitude: ",
                  dmLon,
                  " Altitude (km): ",
                  alt,
                  sep='')
            satOrb = Orbital(station, tle)

            print()

            PrintFreqData(
                GetFreqData(
                    station,
                    "C:/Users/Jake/Python/Satellite Tracker/frequencies/satfreqlist.csv"
                ))

            passes = satOrb.get_next_passes(datetime.utcnow(), 120,
                                            -90.5546910, 38.6475290, 180.85)

            print("Next passes in 5 days (Max Elevation Above 20 deg):")

            for eachPass in passes:
                rise = eachPass[0]
                fall = eachPass[1]
                apex = eachPass[2]

                # Lon, Lat
                obsRiseAngle, obsRiseElv = satOrb.get_observer_look(
                    rise, -90.5546910, 38.6475290, 180.85)
                obsFallAngle, obsFallElv = satOrb.get_observer_look(
                    fall, -90.5546910, 38.6475290, 180.85)
                obsApexAngle, obsApexElv = satOrb.get_observer_look(
                    apex, -90.5546910, 38.6475290, 180.85)

                if obsApexElv >= 20.0:
                    print("Rise Time:", rise, "Azimuth:",
                          round(obsRiseAngle, 2), '(',
                          AzimuthDirection(obsRiseAngle), ')', "Elevation:",
                          abs(round(obsRiseElv, 2)))

                    print("Apex Time:", apex, "Azimuth:",
                          round(obsApexAngle, 2), '(',
                          AzimuthDirection(obsApexAngle), ')', "Elevation:",
                          abs(round(obsApexElv, 2)))

                    print("Fall Time:", fall, "Azimuth:",
                          round(obsFallAngle, 2), '(',
                          AzimuthDirection(obsFallAngle), ')', "Elevation:",
                          abs(round(obsFallElv, 2)))
                    print()
    except:
        pass
Beispiel #19
0
1 43803U 18099AX  19134.16991763  .00000149  00000-0  18753-4 0  9997
2 43803  97.7441 206.5509 0016839  88.1084 272.2065 14.95242491 24118"""
tle = StringIO()
tle.write(amateur_file)
orb = Orbital(
    "AO-7",
    line1=
    "1 07530U 74089B   19134.19581420 -.00000034  00000-0  67853-4 0  9992",
    line2=
    "2 07530 101.7410 102.2252 0012571  56.5062  14.6811 12.53638015 36076")
now = datetime.utcnow()
# arrayat=Orbital.get_observer_look(lon=120.77,lat=15.15,alt=0.020)
pprint(orb)
# >>> # Get longitude, latitude and altitude of the satellite: >>>
pprint(orb.get_lonlatalt(now))
passes = orb.get_next_passes(now, length=4, lon=120.77, lat=15.15, alt=0.02)
#
# Each Pass a tuple of 3, rise, set, max ele
#
start_pass = passes[0][0]
end_pass = passes[0][1]
min_elevation = 10
while (start_pass < end_pass):
    sky_location = orb.get_observer_look(start_pass,
                                         lon=120.77,
                                         lat=15.15,
                                         alt=0.02)
    if sky_location[1] >= min_elevation:
        print("Az  {:6.2f}  Ele {:6.2f} ".format(sky_location[0],
                                                 sky_location[1]))
Beispiel #20
0
    def run(self):
        inpt = 'start'
        while len(inpt) > 0 and not self.stop:
            try:
                inpt = self.skt.recv(1024)

            except:
                pass

            now = datetime.utcnow()
            passes = [[now, now, now]]
            if (now - self.last_update).total_seconds() > self.update_period:
                try:
                    print("updating tle file")
                    data = urllib.request.urlopen(
                        "https://www.amsat.org/tle/current/nasa.all")
                    file = open("tle.txt", 'w')
                    for line in data:
                        file.write(line.decode("utf-8"))
                    file.close()
                    self.last_update = now
                    print("tle file updated")
                except:
                    print("could not update tle file")

            try:
                now = datetime.utcnow()
                orb = Orbital(self.name, tle_file=self.tle_location)
                loc = orb.get_lonlatalt(datetime.utcnow())

                packet = "\x01".encode()

                packet += bytearray(struct.pack("f", loc[0]))
                packet += bytearray(struct.pack("f", loc[1]))
                packet += bytearray(struct.pack("f", loc[2]))
                #send location packet
                try:
                    self.skt.send(packet)
                except:
                    print("could not send packet")

                time.sleep(1)
                now = datetime.utcnow()

                next_passes = orb.get_next_passes(now,
                                                  24,
                                                  -122.3032,
                                                  47.655548,
                                                  150,
                                                  tol=0.001,
                                                  horizon=0)

                if len(next_passes) > 0:
                    #check if both rise and fall are in the future or both in the past
                    if ((passes[0][0] - now).total_seconds()) * (
                        (passes[0][1] - now).total_seconds()) >= 0:
                        passes = next_passes

                rise = (passes[0][0] - now).total_seconds()

                fall = (passes[0][1] - now).total_seconds()
                packet = "\x02".encode()
                packet += bytearray(struct.pack("i", int(rise)))
                packet += bytearray(struct.pack("i", int(fall)))

                #send time packet
                try:
                    self.skt.send(packet)
                except:
                    print("could not send packet")
            except:
                print("could not read tle file at " + self.tle_location)
        print("connection to " + addr[0] + " closed")
        self.skt.close()