Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active August 10, 2018 08:41
Show Gist options
  • Save komasaru/098062763d6b5dcf1eda4ac64d5184cc to your computer and use it in GitHub Desktop.
Save komasaru/098062763d6b5dcf1eda4ac64d5184cc to your computer and use it in GitHub Desktop.
Ruby script to get TLE from NASA.
#! /usr/local/bin/ruby
#=直近 TLE データ取得 (from NASA)
# : 過去の直近の TLE データ1件を取得する
# (過去データが存在しなければ、未来の直近データ)
#
# date name version
# 2018.06.11 mk-mode.com 1.00 新規作成
#
# Copyright(C) 2018 mk-mode.com All Rights Reserved.
#---------------------------------------------------------------------------------
# 引数 : [YYYYMMDD[HHMMSS]]
# (JST を指定。無指定なら現在時刻とみなす)
#---------------------------------------------------------------------------------
#++
require 'time'
require 'open-uri'
require 'timeout'
class TleIssNasa
URL = "https://spaceflight.nasa.gov/realdata/sightings/SSapplications/Post/JavaSSOP/orbit/ISS/SVPOST.html"
UA = "XXXXXXX Bot (by Ruby/#{RUBY_VERSION}, Administrator: MAIL_ADDRESS)"
TIMEOUT = 60
def initialize
if arg = ARGV.shift
begin
@jst = Time.strptime(arg.ljust(14, "0"), "%Y%m%d%H%M%S")
rescue => e
$stderr.puts "Invalid date!"
$stderr.puts "[USAGE] ./tle_iss_nasa.rb [YYYYMMDD[HHMMSS]]"
exit 1
end
else
@jst = Time.now
end
end
def exec
tle = ""
utc_tle = nil
begin
puts @jst.strftime("%Y-%m-%d %H:%M:%S.%6N %Z")
puts @jst.utc.strftime("%Y-%m-%d %H:%M:%S.%6N %Z")
puts "---"
get_tle.reverse.each do |new|
tle = new
item_utc = tle.split(/\s+/)[3]
y = 2000 + item_utc[0, 2].to_i
d = item_utc[2..-1].to_f
jst = Time.new(y, 1, 1) + d * 24 * 60 * 60 + 9 * 60 * 60
utc_tle = jst.utc
break if jst.utc <= @jst.utc
end
puts tle
puts utc_tle.strftime("(%Y-%m-%d %H:%M:%S.%6N %Z)")
rescue => e
$stderr.puts "[#{e.class}] #{e.message}"
e.backtrace.each { |tr| $stderr.puts "\t#{tr}" }
exit 1
end
end
private
# 最新 TLE 一覧取得
def get_tle
html, charset, status, reason = get_html
if status != "200" || reason != "OK"
$stderr.puts "STATUS: #{status} (#{reason})"
$stderr.puts "[ERROR] Could not retreive html."
exit 1
end
return html.scan(/ISS\n +(1.+?)\n +(2.+?)\n/m).map { |a, b| "#{a}\n#{b}"}
rescue => e
raise
end
# HTML 取得
def get_html
status, reason = nil, nil
charset = nil
html = nil
begin
Timeout.timeout(TIMEOUT) do
html = open(URL, "r:utf-8", {"User-Agent" => UA}) do |f|
charset = f.charset
status, reason = f.status
f.read
end
end
return [html, charset, status, reason]
rescue => e
raise
end
end
end
TleIssNasa.new.exec if __FILE__ == $0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment