def get_speed_iss_pos(self,ignore_db_insert=False,testing_mode=None): if testing_mode: self.timestamp = testing_mode['timestamp'] self.latitude = testing_mode['latitude'] self.longitude = testing_mode['longitude'] else: gps_location = self.get_iss_lat_lon() self.timestamp = gps_location['timestamp'] self.latitude = gps_location['latitude'] self.longitude = gps_location['longitude'] if not ignore_db_insert: # Write location stats to DB self.insert_record_in_db(self.latitude, self.longitude, self.timestamp) # global lat_pre,lon_pre, self.timestamp_pre iss = (self.latitude, self.longitude) time_diff = self.timestamp - self.timestamp_pre distance = geodesic((self.lat_pre,self.lon_pre),iss).km self.lat_pre,self.lon_pre = iss self.timestamp_pre = self.timestamp try: speed = distance/time_diff*3600 # km/h except ZeroDivisionError: speed = 0 except Exception as e: logger.error(e) speed = 99999999999 return [speed, iss]
def get_mapbox_token(env_var_name): try: mapbox_access_token = open(os.getenv(env_var_name)).read() logger.debug(f'MAPBOX Access Token: {mapbox_access_token}') return False, mapbox_access_token except TypeError: logger.error('Not a valid token. MAPBOX chart will be disabled') return True, None
def __init__(self): gps_location = self.get_iss_lat_lon() self.timestamp = gps_location['timestamp'] self.latitude = gps_location['latitude'] self.longitude = gps_location['longitude'] try: logger.info('Establishing connection to DB') self.db_cnx = MySql() except Exception: logger.error('DB connection failed') self.db_cnx = None
def get_city_location(city_name): try: location = geolocator.geocode(city_name) if not location: logger.error(f'"{city_name}" is not a valid city name') return 'Invalid','0.0','0.0' logger.info(location) logger.debug(location.address+"Latitude: "+location.raw['lat']) logger.debug(location.address+"Longitude: "+location.raw['lon']) except Exception as e: logger.error(f'Encountered {e} while trying to get city location') return 'Invalid','0.0','0.0' return location.address, location.raw['lat'], location.raw['lon']
def main(): try: st.title('International Space Station Tracker') st.markdown(information['header1']) st.markdown(information['what']) st.markdown(information['intro_source'],unsafe_allow_html=True) st.markdown(information['header2']) st.markdown(information['tech_spec'], unsafe_allow_html=True) st.markdown(information['intro_source'],unsafe_allow_html=True) st.sidebar.markdown(information['profile'],unsafe_allow_html=True) iss = TrackerISS() live_show = st.radio("Show live tracking in orthographic",('Yes', 'No'), index=1) if live_show == 'Yes': home_name_st = st.text_input('Distance relative to (city)',value='') if home_name_st: home_name, home_lat, home_lon = get_city_location(home_name_st) earth = BasemapPlot(home_name,home_lat,home_lon) while live_show == 'Yes' and home_name_st: earth.plot_location(iss.get_speed_iss_pos()) with st.spinner('Reloading in 5 seconds..'): time.sleep(5) mapbox_disable,mapbox_access_token = get_mapbox_token(env_var_name='MAPBOX_TOKEN') if not mapbox_disable: st.write("Current ISS location in flat view") location = iss.get_speed_iss_pos() fig = get_plotly_figure(location,token=mapbox_access_token) if st.button('Refresh'): pass st.plotly_chart(fig) st.write("Predict next ISS pass through by city") predict_city = st.text_input('Enter city name',value='London') if predict_city: _, predict_city_lat, predict_city_lon = get_city_location(predict_city) pass_information=iss.get_pass_info_from_lat_lon(predict_city_lat,predict_city_lon) display_pass_statistics(pass_information) except Exception as e: logger.error('Failed {}'.format(e)) raise Exception(e)
def get_pass_info_from_lat_lon(lat=None,lon=None,testing_mode=None): if testing_mode: pass_url = TrackerISS.pass_link.replace('LAT', str(testing_mode['latitude'])).replace('LON', str(testing_mode['longitude'])) else: pass_url = TrackerISS.pass_link.replace('LAT', str(lat)).replace('LON', str(lon)) try: logger.info(f'Getting ISS pass through info for lat:{lat},lon:{lon}') response = url.urlopen(pass_url) except url.HTTPError as e: logger.error(f'HTTP error while opening URL "{pass_url}"; Bad request: Error code:{e.code}') return 'failure' json_res = json.loads(response.read()) if json_res['message'] == 'success': return json_res['response'] else: return json_res['message']
def insert_record(self, table_name, key_values): ''' Function to insert records in the table. arg: table_name = Name of the table into which records to be inserted. (str) arg: key_values = Dictionary of key value pairs where key is the column name value is the entry corresponding to that key. return: None''' if key_values == '': key_values = {} try: self.cursor = self.connection.cursor() add_record = ("INSERT INTO location " "(lat,lon,datetime_id) " " VALUES (%(lat)s, %(lon)s, %(datetime_id)s)") self.cursor.execute(add_record, key_values) self.connection.commit() except Exception as err: logger.error("Unable to insert records: Error: {}".format(err))
def __init__(self): try: self.connection = mysql.connector.connect(**self.config) logger.info('DB connection successful') except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: logger.error('Incorrect user name or password') elif err.errno == errorcode.ER_BAD_DB_ERROR: logger.error('Database does not exist') elif err.errno == 2003: logger.error('Cant connect to Database') else: raise ('Unknown Error connecting to Database')