-
-
Save nivertech/1754064 to your computer and use it in GitHub Desktop.
Submit BBC Programme Now and Next to MQTT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'rubygems' | |
require 'json' | |
require 'net/http' | |
require 'uri' | |
require 'mqtt' | |
require 'pp' | |
NOW_NEXT_RADIO_URL = 'http://www.bbc.co.uk/iplayer/ion/multinownext/service_type/radio/format/json' | |
NOW_NEXT_TV_URL = 'http://www.bbc.co.uk/iplayer/ion/multinownext/service_type/tv/format/json' | |
def get_json(url) | |
uri = URI.parse(url) | |
res = Net::HTTP.start(uri.host, uri.port) do |http| | |
http.get(uri.request_uri) | |
end | |
if res.code == '200' | |
JSON.parse(res.body) | |
end | |
end | |
$cache = {} | |
def publish(topic, payload) | |
if $cache[topic] != payload | |
$mqtt.publish(topic, payload, retain=true) | |
$cache[topic] = payload | |
end | |
end | |
def publish_service(service, now_next, data) | |
unless data.nil? or data.first.nil? | |
data = data.first | |
publish("bbc/#{now_next}/#{service}/pid", data['episode_id']) | |
publish("bbc/#{now_next}/#{service}/title", data['complete_title']) | |
publish("bbc/#{now_next}/#{service}/start", data['start_time_iso']) | |
publish("bbc/#{now_next}/#{service}/end", data['end_time_iso']) | |
end | |
end | |
$mqtt = MQTT::Client.connect( | |
:remote_host => 'test.mosquitto.org', | |
:client_id => 'ruby_bbc_now_next' | |
) | |
# FIXME: Start with the values on the broker | |
# and pre-populate the cache | |
#$mqtt.subscribe('bbc/now/#') | |
#$mqtt.subscribe('bbc/next/#') | |
def process_services(url) | |
data = get_json(url) | |
unless data.nil? | |
data['blocklist'].each do |service| | |
publish_service(service['id'], 'now', service['now']) | |
publish_service(service['id'], 'next', service['next']) | |
end | |
end | |
end | |
loop do | |
process_services(NOW_NEXT_TV_URL) | |
process_services(NOW_NEXT_RADIO_URL) | |
# Wait until the start of the next minute | |
# FIXME: wait until the next programme ends | |
sleep(60 - Time.now.sec) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment