Ruby Examples

From Open Rail Data Wiki
Jump to navigation Jump to search

Install the Stomp gem with gem install stomp.

The following code will connect to the datafeeds service, subscribe to the the RTPPM feed and print all messages to STDOUT.

To subscribe to multiple topics in a single connection, copy the client.subscribe section of code, change the topic name and the '-RTPPM' suffix

require "stomp"

class NrPollerPoller

  # Initialize the poller

  def initialize

    @hostname = 'publicdatafeeds.networkrail.co.uk'
    @username = 'nobody@example.com'
    @password = 'topsecretpassword'

    puts "Stomp consumer for Network Rail Open Data Distribution Service"

  end


  # Connect to the service and process messages

  def run

    client_headers = { "accept-version" => "1.1", "heart-beat" => "5000,10000", "client-id" => Socket.gethostname, "host" => @hostname }
    client_hash = { :hosts => [ { :login => @username, :passcode => @password, :host => @hostname, :port => 61618 } ], :connect_headers => client_headers }

    client = Stomp::Client.new(client_hash)

    # Check we have connected successfully

    raise "Connection failed" unless client.open?
    raise "Connect error: #{client.connection_frame().body}" if client.connection_frame().command == Stomp::CMD_ERROR
    raise "Unexpected protocol level #{client.protocol}" unless client.protocol == Stomp::SPL_11

    puts "Connected to #{client.connection_frame().headers['server']} server with STOMP #{client.connection_frame().headers['version']}"


    # Subscribe to the RTPPM topic and process messages

    client.subscribe("/topic/RTPPM_ALL", { 'id' => client.uuid(), 'ack' => 'client', 'activemq.subscriptionName' => Socket.gethostname + '-RTPPM' }) do |msg|

      puts msg.body
      client.acknowledge(msg, msg.headers)

    end

    client.join


    # We will probably never end up here

    client.close
    puts "Client close complete"

  end

end

e = NrPollerPoller.new
e.run


Network Rail Open Data Feeds
Data Feeds About the Feeds Account States Durable Subscriptions Example Code ( PHP / C# / Java / Ruby / Node.js) • Advanced UsesFAQ Release Notes
RTPPM RTPPM Feed
Train Movements Train Movements Feed Train Activation Train Cancellation Train Movement Train Reinstatement Change of Origin Change of Identity Change of Location TSPEED Field Planned Cancellations Cancellation Codes
TD TD Feed C-Class Messages S-Class Messages Train Describers TD Berths
VSTP VSTP Feed
TSR TSR Feed Route Codes
SCHEDULE SCHEDULE Feed Schedule and Location Records Association Records CIF Codes How Scheduling Works Allowances
Reference Data Reference Data Feed TOC Codes CIF Codes Delay Attribution Codes Identifying Locations (STANOX, TIPLOC, NLC and 3-Alpha Codes) STANOX Geographical Areas Train Planning data