def test_authenticate():
    def request_callback(request):
        if 'wrongpassword' in request.body:
            return (200, dict(), json.dumps({'Login': '******'}))
        elif 'unknownresponse' in request.body:
            # Space-Track doesn't respond like this, but make sure anything
            # other than {'Login': '******'} doesn't raise AuthenticationError
            return (200, dict(), json.dumps({'Login': '******'}))
        else:
            return (200, dict(), json.dumps(''))

    responses.add_callback(responses.POST,
                           'https://www.space-track.org/ajaxauth/login',
                           callback=request_callback,
                           content_type='application/json')

    st = SpaceTrackClient('identity', 'wrongpassword')

    with pytest.raises(AuthenticationError):
        st.authenticate()

    assert len(responses.calls) == 1

    st.password = '******'
    st.authenticate()
    st.authenticate()

    # Check that only one login request was made since successful
    # authentication
    assert len(responses.calls) == 2

    st = SpaceTrackClient('identity', 'unknownresponse')
    st.authenticate()
def get_spacetrack_tle(sat_id,
                       start_date,
                       end_date,
                       username,
                       password,
                       latest=False):
    st = SpaceTrackClient(identity=username, password=password)
    if not latest:
        daterange = op.inclusive_range(start_date, end_date)
        data = st.tle(norad_cat_id=sat_id,
                      orderby='epoch desc',
                      limit=1,
                      format='tle',
                      epoch=daterange)
    else:
        data = st.tle_latest(norad_cat_id=sat_id,
                             orderby='epoch desc',
                             limit=1,
                             format='tle')

    if not data:
        return 0, 0

    tle_1 = data[0:69]
    tle_2 = data[70:139]
    return tle_1, tle_2
Example #3
0
def build_space_track_client(username, password, log_delay=True):
    stc = SpaceTrackClient(identity=username, password=password)
    if log_delay:
        # Add a call back to the space track client that logs
        # when the client has to sleep to abide by the rate limits
        stc.callback = st_callback
    return stc
Example #4
0
def main(noradID, path):

    st = SpaceTrackClient('*****@*****.**', 'COSGCGroundSegment')

    try:
        st.authenticate()  # Will raise an error if incorrect login
    except:
        print('Incorrect Login.')
        sys.exit(0)

    data = st.tle_latest(iter_lines=True,
                         norad_cat_id=noradID,
                         limit=1,
                         format='3le')
    # Change format to whatever is easiest

    line1 = next(data)  # 0 MINXSS
    line2 = next(data)  # 1 blah blah
    line3 = next(data)  # 2 blah blah

    outFile = path + line1.split()[1] + '.txt'

    # Need to split up the generator to get the name for above.
    with open(outFile, 'w+') as f:
        f.write(line1)
        f.write(line2)
        f.write(line3)
Example #5
0
def main():
    st = SpaceTrackClient('user', 'pw')
    ids = [25544, 20580, 27540, 28485, 31135,\
       33053, 41765, 40889, 40890,\
       41175, 41174, 41550, 41549, 41859,\
       41860, 41861, 41862, 23118, 28378]
    lines = st.tle_latest(iter_lines=True,
                          epoch='>now-30',
                          orderby='epoch',
                          norad_cat_id=ids,
                          format='tle')
    satDic = {}
    for id in ids:
        satDic[id] = []
    for line in lines:
        for id in ids:
            if str(id) in line:
                satDic[id].append(line)

    for id, line in satDic.items():
        with open('satellites/' + str(id) + '.dat', 'w') as fp:
            if not len(line) < 2:
                fp.write(line[-2] + "\n")
                fp.write(line[-1] + "\n")
            else:
                fp.write("\n")
Example #6
0
def test_generic_request_exceptions():
    st = SpaceTrackClient('identity', 'password')

    with pytest.raises(ValueError):
        st.generic_request(class_='tle', iter_lines=True, iter_content=True)

    with pytest.raises(ValueError):
        st.generic_request(class_='thisclassdoesnotexist')

    def mock_get_predicates(self, class_):
        return []

    patch_authenticate = patch.object(SpaceTrackClient, 'authenticate')

    patch_get_predicates = patch.object(SpaceTrackClient, 'get_predicates',
                                        mock_get_predicates)

    with patch_authenticate, patch_get_predicates:
        with pytest.raises(TypeError):
            st.generic_request('tle', madeupkeyword=None)

    with pytest.raises(ValueError):
        st.generic_request(class_='tle', controller='nonsense')

    with pytest.raises(ValueError):
        st.generic_request(class_='nonsense', controller='basicspacedata')

    with pytest.raises(AttributeError):
        st.basicspacedata.blahblah
Example #7
0
def get_spacetrack_tle(sat_id,
                       start_date,
                       end_date,
                       username,
                       password,
                       latest=False):
    # Реализуем экземпляр класса SpaceTrackClient, инициализируя его именем пользователя и паролем
    st = SpaceTrackClient(identity=username, password=password)
    # Выполнение запроса для диапазона дат:
    if not latest:
        # Определяем диапазон дат через оператор библиотеки
        daterange = op.inclusive_range(start_date, end_date)
        # Собственно выполняем запрос через st.tle
        data = st.tle(norad_cat_id=sat_id,
                      orderby='epoch desc',
                      limit=1,
                      format='tle',
                      epoch=daterange)
    # Выполнение запроса для актуального состояния
    else:
        # Выполняем запрос через st.tle_latest
        data = st.tle_latest(norad_cat_id=sat_id,
                             orderby='epoch desc',
                             limit=1,
                             format='tle')

    # Если данные недоступны
    if not data:
        return 0, 0

    # Иначе возвращаем две строки
    tle_1 = data[0:69]
    tle_2 = data[70:139]
    return tle_1, tle_2
Example #8
0
def get_sat(norad_id):
    """Download a TLE and plot it
    """
    from spacetrack import SpaceTrackClient
    logger = logging.getLogger(__name__)

    logger.info('Getting SpaceTrack password and connecting')
    username = input('Enter SpaceTrack.org username: '******'Enter SpaceTrack.org password: '******'3le')
    ]

    # parse the tle
    if validtle(lines[0], lines[1], lines[2]):
        # now we parse the tle
        elements = parsetle(lines[0], lines[1], lines[2])
        # final check to see if we got a good TLE
        if elements.good:
            # instantiate a bunch of instances of a Satellite class
            sat = Satellite(elements)

    return sat
def test_ratelimit_error():
    responses.add(responses.POST,
                  'https://www.space-track.org/ajaxauth/login',
                  json='""')

    responses.add(
        responses.GET,
        'https://www.space-track.org/basicspacedata/modeldef/class/tle_publish',
        json={
            'controller':
            'basicspacedata',
            'data': [{
                'Default': '0000-00-00 00:00:00',
                'Extra': '',
                'Field': 'PUBLISH_EPOCH',
                'Key': '',
                'Null': 'NO',
                'Type': 'datetime'
            }, {
                'Default': '',
                'Extra': '',
                'Field': 'TLE_LINE1',
                'Key': '',
                'Null': 'NO',
                'Type': 'char(71)'
            }, {
                'Default': '',
                'Extra': '',
                'Field': 'TLE_LINE2',
                'Key': '',
                'Null': 'NO',
                'Type': 'char(71)'
            }]
        })

    responses.add(
        responses.GET,
        'https://www.space-track.org/basicspacedata/query/class/tle_publish',
        status=500,
        body='violated your query rate limit')

    st = SpaceTrackClient('identity', 'password')

    # Change ratelimiter period to speed up test
    st._ratelimiter.period = 1

    # Do it first without our own callback, then with.

    # Catch the exception when URL is called a second time and still gets HTTP 500
    with pytest.raises(HTTPError):
        st.tle_publish()

    mock_callback = Mock()
    st.callback = mock_callback

    # Catch the exception when URL is called a second time and still gets HTTP 500
    with pytest.raises(HTTPError):
        st.tle_publish()

    assert mock_callback.call_count == 1
Example #10
0
    def pull_catalogue(self):
        st = SpaceTrackClient(identity=self.user, password=self.password)
        st_data = st.satcat()
        # st_data = st.satcat(norad_cat_id=ids)

        intldes = list()  # do we need this?
        norad_cat_id = list()
        object_type = list()
        country = list()
        decay = list()
        launch_year = list()

        # dict to df (might change to json later)
        for dict in st_data:
            print(dict['INTLDES'])
            intldes.append(dict['INTLDES'])
            norad_cat_id.append(dict['NORAD_CAT_ID'])
            object_type.append(dict['OBJECT_TYPE'])
            country.append(dict['COUNTRY'])
            decay.append(dict['DECAY'])
            launch_year.append(dict['LAUNCH_YEAR'])

        st_df = pd.DataFrame(list(
            zip(intldes, norad_cat_id, object_type, country, decay,
                launch_year)),
                             columns=[
                                 'INTLDES', 'NORAD_CAT_ID', 'OBJECT_TYPE',
                                 'COUNTRY', 'DECAY', 'LAUNCH_YEAR'
                             ])

        return (st_df)
Example #11
0
def test_parse_types():
    responses.add(responses.POST,
                  'https://www.space-track.org/ajaxauth/login',
                  json='""')

    responses.add(
        responses.GET,
        'https://www.space-track.org/basicspacedata/modeldef/class/tle_publish',
        json={
            'controller':
            'basicspacedata',
            'data': [{
                'Default': '0000-00-00 00:00:00',
                'Extra': '',
                'Field': 'PUBLISH_EPOCH',
                'Key': '',
                'Null': 'NO',
                'Type': 'datetime'
            }, {
                'Default': '',
                'Extra': '',
                'Field': 'TLE_LINE1',
                'Key': '',
                'Null': 'NO',
                'Type': 'char(71)'
            }, {
                'Default': '',
                'Extra': '',
                'Field': 'TLE_LINE2',
                'Key': '',
                'Null': 'NO',
                'Type': 'char(71)'
            }]
        })

    responses.add(
        responses.GET,
        'https://www.space-track.org/basicspacedata/query/class/tle_publish',
        json=[{
            # Test a type that is parsed.
            'PUBLISH_EPOCH': '2017-01-02 03:04:05',
            # Test a type that is passed through.
            'TLE_LINE1': 'The quick brown fox jumps over the lazy dog.',
            # Test a field there was no predicate for.
            'OTHER_FIELD': 'Spam and eggs.'
        }])

    st = SpaceTrackClient('identity', 'password')

    result, = st.tle_publish(parse_types=True)
    assert result['PUBLISH_EPOCH'] == dt.datetime(2017, 1, 2, 3, 4, 5)
    assert result[
        'TLE_LINE1'] == 'The quick brown fox jumps over the lazy dog.'
    assert result['OTHER_FIELD'] == 'Spam and eggs.'

    with pytest.raises(ValueError) as exc_info:
        st.tle_publish(format='tle', parse_types=True)

    assert 'parse_types' in exc_info.value.args[0]
Example #12
0
def test_get_predicates_exceptions():
    st = SpaceTrackClient('identity', 'password')

    with pytest.raises(ValueError):
        st.get_predicates(class_='tle', controller='nonsense')

    with pytest.raises(ValueError):
        st.get_predicates(class_='nonsense', controller='basicspacedata')
Example #13
0
 def __init__(self):
     """
     Connects user to Space-Track account
     """
     un, pw = self.requestAccess()
     self.username = un
     self.password = pw
     self.client = SpaceTrackClient(identity=un, password=pw)
Example #14
0
def getTles():
	catalog_number = 39161
	for line in open('/home/rasmus/catkin_ws/src/antenna_controller/tle/current_satellite.txt','r').readlines():
		catalog_number = int(line)
	st = SpaceTrackClient('*****@*****.**', '!kK!Ft3-W6sKGa8X')
	tle = st.tle_latest(norad_cat_id=catalog_number, ordinal=1, format='3le').encode("utf-8")
	rospy.loginfo(tle)
	formatTle(tle)
Example #15
0
def get_TLE_data( norad_ids:list[int]) -> list[dict]:

    USR = auth["USR"]
    PASS = auth["PASS"]
    st = SpaceTrackClient(USR, PASS)
    # ordinal=1 gets only the latest tle for each noradID.
    tle_obj_vec = st.tle_latest(ordinal=1,norad_cat_id=norad_ids, orderby="norad_cat_id")

    return tle_obj_vec
Example #16
0
def run_sim():
    start_jd, _ = time.date2jd(2017, 10, 1, 0, 0, 0)
    end_jd, _ = time.date2jd(2017, 10, 2, 0, 0, 0)
    num_sec = (end_jd - start_jd) * 86400
    num_steps = 1e4
    t_step = num_sec / num_steps  # time step in Julian days

    RelTol = 1e-6
    AbsTol = 1e-6

    sat = satellite.Satellite()

    # define the initial state as the ISS
    download = False
    if download:
        from spacetrack import SpaceTrackClient
        password = input('Enter SpaceTrack password: '******'shanks.k', password)
        iss_tle = st.tle_latest(norad_cat_id=[25544], format='3le', ordinal=1)

        with open('./data/iss.txt', 'w') as f:
            f.write(iss_tle)

    sats = tle.get_tle('./data/iss.txt')
    iss = sats[0]
    # propogate to start JD

    iss.tle_update(np.array([start_jd, end_jd]))

    # get r,v vectors
    initial_pos = iss.r_eci[0, :]
    initial_vel = iss.v_eci[0, :]
    initial_R = np.eye(3, 3)
    initial_w = np.zeros(3)

    initial_state = np.concatenate(
        (initial_pos, initial_vel, initial_R.reshape(9), initial_w))

    # setup the integrator
    system = integrate.ode(sat.eoms_inertial_ode)
    system.set_integrator('lsoda', atol=AbsTol, rtol=RelTol, nsteps=num_steps)
    system.set_initial_value(initial_state, 0)

    jd_sim = np.zeros(int(num_steps + 1))
    i_state = np.zeros((int(num_steps + 1), 18))

    i_state[0, :] = initial_state
    jd_sim[0] = start_jd

    ii = 1
    while system.successful() and system.t < (num_sec - t_step):
        jd_sim[ii] = (system.t + t_step) / 86400 + start_jd
        i_state[ii, :] = system.integrate(system.t + t_step)
        ii += 1

    # output state and variables
    return jd_sim, i_state
Example #17
0
def test_controller_spacetrack_methods():
    st = SpaceTrackClient('identity', 'password')
    with patch.object(SpaceTrackClient, 'generic_request') as mock_generic_request:
        for controller, classes in st.request_controllers.items():
            for class_ in classes:
                controller_proxy = getattr(st, controller)
                method = getattr(controller_proxy, class_)
                method()
                expected = call(class_=class_, controller=controller)
                assert mock_generic_request.call_args == expected
Example #18
0
def test_base_url():
    responses.add(responses.POST,
                  'https://example.com/ajaxauth/login',
                  json='""')
    st = SpaceTrackClient('identity',
                          'password',
                          base_url='https://example.com')
    st.authenticate()

    assert len(responses.calls) == 1
def callback(data):
	st = SpaceTrackClient('*****@*****.**', '!kK!Ft3-W6sKGa8X')
	tle = st.tle_latest(norad_cat_id=data.data, ordinal=1, format='3le').encode("utf-8")
	print(tle)
	if not (tle.strip() == ""):
		print(data)
		if (doesSatellitePass(tle)):
			addSatelliteToTrack(data.data)
			tle_getter_node.formatTle(tle)
	else:
		print("Wrong Catalog Number")
Example #20
0
def test_bytes_response():
    responses.add(
        responses.POST, 'https://www.space-track.org/ajaxauth/login', json='""')

    responses.add(
        responses.GET,
        'https://www.space-track.org/fileshare/modeldef/class/download',
        json={
            'controller': 'fileshare',
            'data': [
                {
                    'Default': '0',
                    'Extra': '',
                    'Field': 'FILE_ID',
                    'Key': '',
                    'Null': 'NO',
                    'Type': 'int(10) unsigned'
                },
                {
                    'Default': None,
                    'Extra': '',
                    'Field': 'FILE_CONTENET',
                    'Key': '',
                    'Null': 'YES',
                    'Type': 'longblob'
                }
            ]})

    data = b'bytes response \r\n'

    responses.add(
        responses.GET,
        'https://www.space-track.org/fileshare/query/class/download'
        '/format/stream',
        body=data)

    st = SpaceTrackClient('identity', 'password')
    assert st.download(format='stream') == data

    with pytest.raises(ValueError):
        st.download(iter_lines=True, format='stream')

    # Just use file_id to disambiguate URL from those above
    responses.add(
        responses.GET,
        'https://www.space-track.org/fileshare/query/class/download'
        '/file_id/1',
        body=b'a' * (100 * 1024) + b'b')

    result = list(st.download(
        iter_content=True, file_id=1))

    assert result[0] == b'a' * (100 * 1024)
    assert result[1] == b'b'
Example #21
0
def test_spacetrack_methods():
    """Verify that e.g. st.tle_publish calls st.generic_request('tle_publish')"""
    st = SpaceTrackClient('identity', 'password')
    with patch.object(SpaceTrackClient,
                      'generic_request') as mock_generic_request:
        for class_ in st.request_classes:
            method = getattr(st, class_)
            method()
            assert mock_generic_request.call_args == call(class_)

    with pytest.raises(AttributeError):
        st.madeupmethod()
Example #22
0
def test_non_ratelimit_error():
    responses.add(responses.POST,
                  'https://www.space-track.org/ajaxauth/login',
                  json='""')

    responses.add(
        responses.GET,
        'https://www.space-track.org/basicspacedata/modeldef/class/tle_publish',
        json={
            'controller':
            'basicspacedata',
            'data': [{
                'Default': '0000-00-00 00:00:00',
                'Extra': '',
                'Field': 'PUBLISH_EPOCH',
                'Key': '',
                'Null': 'NO',
                'Type': 'datetime'
            }, {
                'Default': '',
                'Extra': '',
                'Field': 'TLE_LINE1',
                'Key': '',
                'Null': 'NO',
                'Type': 'char(71)'
            }, {
                'Default': '',
                'Extra': '',
                'Field': 'TLE_LINE2',
                'Key': '',
                'Null': 'NO',
                'Type': 'char(71)'
            }]
        })

    st = SpaceTrackClient('identity', 'password')

    # Change ratelimiter period to speed up test
    st._ratelimiter.period = 1

    mock_callback = Mock()
    st.callback = mock_callback

    responses.add(
        responses.GET,
        'https://www.space-track.org/basicspacedata/query/class/tle_publish',
        status=500,
        body='some other error')

    with pytest.raises(HTTPError):
        st.tle_publish()

    assert not mock_callback.called
Example #23
0
def download_tle():
    """
    Because the API is unstable, we can download it for testing
    """
    user = ""
    password = ""
    c = SpaceTrackClient(user, password)
    c.authenticate()
    data = c.get_space_debris()
    with open('tle.txt', 'w') as f:
        f.write(data)
    c.close()
 def callback(self, data):
     catalog_number = data.data
     st = SpaceTrackClient('*****@*****.**', '!kK!Ft3-W6sKGa8X')
     tle = st.tle_latest(norad_cat_id=catalog_number,
                         ordinal=1,
                         format='3le').encode("utf-8").strip()
     if not (tle == ""):
         if self.does_satellite_pass(tle, catalog_number):
             self.add_satellite_to_track(catalog_number)
             tle_getter_node.format_tle(tle)
     else:
         rospy.loginfo("{}: Wrong Catalog Number".format(catalog_number))
def main():
    st = SpaceTrackClient('user', 'pw')
    ids = [20580, 27540, 28485, 31135, 33053, 36577, 25544, 37820, 41765]
    for i in ids:
        lines = st.tle_latest(iter_lines=True,
                              epoch='>now-30',
                              limit=1,
                              orderby='epoch',
                              norad_cat_id=i,
                              format='tle')
        with open('satellites/' + str(i) + '.dat', 'w') as fp:
            for line in lines:
                fp.write(line + "\n")
Example #26
0
def getSatCat(name='', pw='',
              le_format='3le'):
    """
    Retrieves full catalog of latest elsets in requested format
    
    Parameters
    ----------
    name : str
        Username for access to the Space-Track database
        Default = '' 
    pw : str
        Password for access to the Space-Track database
        Default = ''
    le_format : str
        Format of the retrieved line element sets
        'tle' - returns two line elements
        '3le' - returns three line elements (includes sat names)
        Default = '3le'
    
    Returns
    -------
    None
    
    Raises
    ------
    None
    """ 
    st = SpaceTrackClient(identity=name, password=pw)
    
    data = st.tle_latest(iter_lines=True, epoch='>now-30', ordinal=1, format=le_format)
    
    # get datestamp
    date = datetime.datetime.now()
    date_str = date.strftime('%Y%m%d')
    mth = str(date.month) + '/'
    yr = str(date.year) + '/'
    
    # get filepath
    filepath = dirname(realpath(__file__)) + '/'
    
    if not isdir(filepath + yr):
        mkdir(filepath + yr)
    
    if not isdir(filepath + yr + mth):
        mkdir(filepath + yr + mth)
    
    with open(filepath + yr + mth + '/tle_' + date_str + '.txt', 'w') as f:
        for line in data:
            f.write(line + '\n')
    
    return None
def getTle():
    st = SpaceTrackClient('*****@*****.**', '!kK!Ft3-W6sKGa8X')
    tle = st.tle_latest(norad_cat_id=39161, ordinal=1,
                        format='3le').encode("utf-8")

    lines = tle.splitlines()
    lines[0] = lines[0][2:len(lines[0])]

    with open('/home/rasmus/catkin_ws/src/antenna_controller/tle/tle.txt',
              'w') as f:
        f.write("{}\n{}\n{}".format(lines[0], lines[1], lines[2]))

    print(tle)
    return lines
Example #28
0
def test_predicate_parse():
    st = SpaceTrackClient('identity', 'password')

    predicates_data = [{
        'Default': '',
        'Extra': '',
        'Field': 'TEST',
        'Key': '',
        'Null': 'NO',
        'Type': '%brokentype'
    }]

    with pytest.raises(ValueError):
        st._parse_predicates_data(predicates_data)

    predicates_data = [{
        'Default': '',
        'Extra': '',
        'Field': 'TEST',
        'Key': '',
        'Null': 'NO',
        'Type': 'unknowntype'
    }]

    with pytest.raises(ValueError):
        st._parse_predicates_data(predicates_data)

    predicates_data = [{
        'Default': '',
        'Extra': '',
        'Field': 'TEST',
        'Key': '',
        'Null': 'NO',
        'Type': 'enum()'
    }]

    with pytest.raises(ValueError):
        st._parse_predicates_data(predicates_data)

    predicates_data = [{
        'Default': '',
        'Extra': '',
        'Field': 'TEST',
        'Key': '',
        'Null': 'NO',
        'Type': "enum('a','b')"
    }]

    predicate = st._parse_predicates_data(predicates_data)[0]
    assert predicate.values == ('a', 'b')
Example #29
0
 def callback(self, data):
     catalog_number = data.data
     st = SpaceTrackClient('*****@*****.**', '!kK!Ft3-W6sKGa8X')
     tle = st.tle_latest(norad_cat_id=catalog_number,
                         ordinal=1,
                         format='3le').encode("utf-8").strip()
     print(tle)
     if not (tle == ""):
         print(data)
         if (self.doesSatellitePass(tle, catalog_number)):
             self.addSatelliteToTrack(catalog_number)
             tle_getter_node.TLEGetter().formatTle(tle)
     else:
         print("{}: Wrong Catalog Number".format(catalog_number))
Example #30
0
    def get_tle(self):
        """
        Replaces the current satellite TLE when needed.
        """

        for line in open(get_tle_file_path('current_satellite.txt'),
                         'r').readlines():
            catalog_number = int(line)
            st = SpaceTrackClient('*****@*****.**',
                                  '!kK!Ft3-W6sKGa8X')
            tle = st.tle_latest(norad_cat_id=catalog_number,
                                ordinal=1,
                                format='3le').encode("utf-8").strip()
            rospy.loginfo(tle)
            format_tle(tle)