Пример #1
0
def callback():
    darwin_session = DarwinLdbSession(wsdl='https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx?ver=2015-05-14', api_key = '6adcdf6a-2b06-40e0-8436-469c4468a679')
    crs_code = "HGY"
    board = darwin_session.get_station_board(crs_code)
    tex.delete(1.0, tk.END)
    s = "\nNext departures for %s" % (board.location_name)
    t = """
-------------------------------------------------------------------------------
|  PLAT  | DEST                                        |   SCHED   |    DUE   |
------------------------------------------------------------------------------- """
    tex.insert(tk.END, s + t)
    tex.see(tk.END)

    for service in board.train_services:
        u = ("| %6s | %43s | %9s | %8s |\n" %(service.platform or "", service.destination_text, service.std, service.etd))
                 # Scroll if necessary
        tex.insert(tk.END, u)
        tex.see(tk.END)
    v = "-------------------------------------------------------------------------------\n"
    tex.insert(tk.END, v)
    tex.see(tk.END)
    timey = time.asctime()
    tex.insert(tk.END, timey)
    
    top.after(1000, callback)
Пример #2
0
def get_train_times(source, dest):
    log.log_message('trains: Getting session')
    session = DarwinLdbSession(wsdl=apis.darwin_api_url,
                               api_key=apis.darwin_api_key)

    log.log_message('trains: Getting train times: ' + source + ' -> ' + dest)
    result = session.get_station_board(source, destination_crs=dest)

    log.log_message('trains: Got times: ' + source + ' -> ' + dest)
    return result
Пример #3
0
def main():
    ap = argparse.ArgumentParser()
    ap.add_argument(
        "station",
        type=str,
        help="station CRS code, e.g. MAN for Manchester Piccadilly")
    ap.add_argument(
        "--destination",
        type=str,
        required=False,
        help="Only include services travelling to this CRS code, e.g HUD",
    )
    ap.add_argument("--csv", action="store_true", help="output in csv format")
    args = ap.parse_args()
    darwin_session = DarwinLdbSession(
        wsdl="https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx")
    # build up query
    board_query = partial(darwin_session.get_station_board, args.station)
    if args.destination:
        board_query = partial(board_query, destination_crs=args.destination)

    # convert to tabular data for display
    board_rows = rows_to_display(board_query())

    # output CSV if requested
    if args.csv:
        output_writer = csv.writer(sys.stdout, dialect="unix")
        output_writer.writerows(board_rows)
        return

    # Otherwise output human readable table
    print(tabulate(board_rows, headers="firstrow"))
def HGY_dep_board():
    darwin_session = DarwinLdbSession(wsdl='https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx?ver=2015-05-14', api_key = '6adcdf6a-2b06-40e0-8436-469c4468a679')

    crs_code = "HGY"

# retrieve departure board
    board = darwin_session.get_station_board(crs_code)

# print table header
    print("\nNext departures for %s" % (board.location_name))
    print("""
-------------------------------------------------------------------------------
|  PLAT  | DEST                                        |   SCHED   |    DUE   |
------------------------------------------------------------------------------- """)

# Loop through services
    for service in board.train_services:
        print("| %6s | %43s | %9s | %8s |" %(service.platform or "", service.destination_text, service.std, service.etd))

 #Print a footer 
    print("-------------------------------------------------------------------------------")
Пример #5
0
    def GetData():
        LiveTime.LastUpdate = datetime.now()
        services = []

        try:
            darwin_sesh = DarwinLdbSession(wsdl="https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx", api_key=Args.APIToken)
            board = darwin_sesh.get_station_board(Args.StationID)
            global StationName
            StationName = board.location_name

            for serviceC in board.train_services:
                if len(services) >= Args.NumberOfCards:
                    break
                service = darwin_sesh.get_service_details(serviceC.service_id)
                if (service.sta != None or service.std != None) and str(service.platform) not in Args.ExcludedPlatforms:
                    services.append(LiveTime(service, len(services) + 1, serviceC))

            return services
        except Exception as e:
            print("GetData() ERROR")
            print(str(e))
            return []
Пример #6
0
 def __init__(self, config):
     self.config = config
     self.service_count = 0
     self.journey_count = 0
     self.darwin_session = DarwinLdbSession(wsdl=config["wsdl"], api_key=config["api_key"])
     self.board = None
     self.displays = []
     # Configure displays
     for display_config in config['displays']:
         # Skip if not enabled
         if display_config['enabled']:
             # Create and store instance
             class_name = display_config['class']
             display_module = __import__('RailDisplay.Display.%s' % class_name, fromlist=["RailDisplay.Display"])
             display_class = getattr(display_module, class_name)
             self.displays.append(display_class(config=display_config, rail=self))
Пример #7
0
    def __init__(self):
        # get the configuration if needed
        try:
            self.config = SnipsConfigParser.read_configuration_file(CONFIG_INI)
        except:
            self.config = None

        api_key = self.config.get("secret").get("nre_api_key")
        self.home_station_code = self.config.get("secret").get(
            "home_station_code")
        self.destination_code = self.config.get("secret").get(
            "destination_code")
        self.darwin_session = DarwinLdbSession(
            wsdl="https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx",
            api_key=api_key)

        # start listening to MQTT
        self.start_blocking()
Пример #8
0
class RailDisplay:

    config = None
    service_count = 0
    journey_count = 0

    def __init__(self, config):
        self.config = config
        self.service_count = 0
        self.journey_count = 0
        self.darwin_session = DarwinLdbSession(wsdl=config["wsdl"], api_key=config["api_key"])
        self.board = None
        self.displays = []
        # Configure displays
        for display_config in config['displays']:
            # Skip if not enabled
            if display_config['enabled']:
                # Create and store instance
                class_name = display_config['class']
                display_module = __import__('RailDisplay.Display.%s' % class_name, fromlist=["RailDisplay.Display"])
                display_class = getattr(display_module, class_name)
                self.displays.append(display_class(config=display_config, rail=self))

    # Update the board
    def update_board(self):
        from_csr = self.config["journey"][self.journey_count]["departure_station"]
        to_csr = self.config["journey"][self.journey_count]["destination_station"]
        self.board = self.darwin_session.get_station_board(from_csr, 10, True, False, to_csr)
        print 'Updating Board'
        self.display_train(self.service_count)

    # Display train details on all configured displays
    def display_train(self, count):
        s = self.board.train_services[count]
        message = s.destination_text + " - " + s.std + " - " + s.etd
        for display in self.displays:
            display.display_message(message)
        # If the train is late, let the display alert
        if s.etd != 'On time':
            for display in self.displays:
                display.alert_late()
Пример #9
0
def initSession():
    newSession = DarwinLdbSession(
        wsdl=
        "https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx?ver=2017-10-01",
        api_key="***REMOVED***")
    return newSession
Пример #10
0
#!/usr/bin/env python

# Customisation variables
# Expects DARWIN_WEBSERVICE_API_KEY environment variable (you will need to sign up for an API key for OpenLDBWS)
# Expects DEPARTURE_CRS_CODE environment variable (e.g. "GTW" - the departure station that we're interested in)
# Expects DESTINATION_CRS_CODE environment variable (e.g. "BTN" - the destination station that we're interested in)
AvailableLEDCount = 8  # Total number of LEDs available; this should be 8 if you're using a Blinkt!

# Uses nre-darwin-py package (install with pip)
from nredarwin.webservice import DarwinLdbSession
from blinkt import set_all, set_pixel, set_clear_on_exit, show
from datetime import datetime, timedelta
import os
import syslog

DarwinSession = DarwinLdbSession(
    wsdl='https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx')
DepartureBoard = DarwinSession.get_station_board(
    os.environ["DEPARTURE_CRS_CODE"],
    destination_crs=os.environ["DESTINATION_CRS_CODE"])

# Initialise lists
ServiceStatus = []
Services = []
LEDs = [0] * AvailableLEDCount

# Populate ServiceStatus and Services.
# White=5=imminent/just left, Green=4=on time, yellow=3=late, blue=2=unspecified delay, red=1=cancelled, black=0=none
# We also check and deal with trains that wrap over midnight
CurrentYMD = datetime.now().strftime("%Y-%m-%d")
CurrentTime = datetime.now()
for service in DepartureBoard.train_services:
Пример #11
0
from nredarwin.webservice import DarwinLdbSession

# initiate a session
# this depends on the DARWIN_WEBSERVICE_API_KEY environment variable
# The WSDL environment variable also allows for
darwin_session = DarwinLdbSession(
    wsdl='https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx')
print("Enter 3 digit CRS code:")
try:
    input = raw_input  #python2 has raw_input, python3 has input
except NameError:
    pass
crs_code = input().upper()

# retrieve departure board
board = darwin_session.get_station_board(crs_code)

# print table header
print("\nNext departures for %s" % (board.location_name))
print("""
-------------------------------------------------------------------------------
|  PLAT  | DEST                                        |   SCHED   |    DUE   |
------------------------------------------------------------------------------- """
      )

# Loop through services
for service in board.train_services:
    print("| %6s | %43s | %9s | %8s |" %
          (service.platform
           or "", service.destination_text, service.std, service.etd))
Пример #12
0
from datetime import timedelta
from datetime import datetime
from nredarwin.webservice import DarwinLdbSession
import csv
from flask import Flask, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy

darwin_sesh = DarwinLdbSession(
    wsdl="https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx",
    api_key="f9548875-c386-45a6-96dc-de1c554da75c")

app = Flask(__name__)

stationDict = {}
#Contains station names and their respective station codes

with open('stationcodes.csv') as stationcodes:
    reader = csv.reader(stationcodes)
    for row in reader:
        stationDict[(row[0].upper())] = row[1]


class station():
    def __init__(self, name, walkingTime=None, destination=None):
        # Initialises the user preferences for their station, the time it takes to get there (optional) and their line (optional)
        self.name = name
        self.walkingTime = walkingTime
        self.destination = destination

    def call(self):
        #Calls the platform board and dispays the results
Пример #13
0
def _get_darwin_session(api_key):
    return DarwinLdbSession(wsdl=DARWIN_WSDL, api_key=api_key)
Пример #14
0
from nredarwin.webservice import DarwinLdbSession
import secrets
from datetime import datetime, time, date, timedelta

darwin_sesh = DarwinLdbSession(
    wsdl="https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx",
    api_key=secrets.api_key)


def get_next_services(station_from, station_to):
    board = darwin_sesh.get_station_board(station_from,
                                          destination_crs=station_to)
    services = board.train_services[0:5]

    for service in services:
        attach_time_until_departure(service)

    return services


def attach_time_until_departure(service):
    try:
        time_of_departure = get_time_of_departure(service)
        datetime_of_departure = get_datetime_from_board_time(time_of_departure)
        service.time_until_departure = datetime_of_departure - datetime.now()
    except:
        pass
        # Don't care if we fail to attach time until departure


# Note: this assumes that the time it is passed is
Пример #15
0
#import urllib
import json
import os
from flask import Flask
from flask import request
from flask import make_response
from nredarwin.webservice import DarwinLdbSession

# initiate a session
# this depends on the DARWIN_WEBSERVICE_API_KEY environment variable
# The WSDL environment variable also allows for
#darwin_session = DarwinLdbSession(wsdl='https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx', api_key="1f21cc57-9942-4e08-9a5d-63f0c2061d02")

app = Flask(__name__)
darwin_session = DarwinLdbSession(
    wsdl='https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx',
    api_key="1f21cc57-9942-4e08-9a5d-63f0c2061d02")


@app.route('/webhook', methods=['POST'])
def webhook():
    req = request.get_json(silent=True, force=True)
    print("Request:")
    print(json.dumps(req, indent=4))

    res = makeWebhookResult(req)
    res = json.dumps(res, indent=4)
    print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r
Пример #16
0
 def darwin_session(self):
     return DarwinLdbSession(
         wsdl="https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx",
         api_key='55ede721-e99e-488b-9087-bcfb611f54f3')
Пример #17
0
from nredarwin.webservice import DarwinLdbSession

darwin_sesh = DarwinLdbSession(wsdl="http://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx", api_key="c879e817-1c98-4aff-9e56-977025775c3b")

count = 0

board = darwin_sesh.get_station_board('GLC')

print(darwin_sesh.get_station_board('GLC'))



while count < 10:
    info = board.train_services[count]
    platforminfo = "Main Concorse"
    if info.platform == "16", "17":
        platforminfo = "Low Level Platform"
    print("Departure No ", count+1, info.std, " ", info.operator_name, " ",info.destination_text, "Platform: ",info.platform, platforminfo)

    service_id = board.train_services[count].service_id
    service = darwin_sesh.
    get_service_details(service_id)
    print ("This train will call at: ", [cp.location_name for cp in service.subsequent_calling_points])
    print ("")
    count  +=1 
print ("****** Additonal Service Information *****")
print (darwin_sesh.get_station_board('GLC').nrcc_messages)
print ("****** END *******")
Пример #18
0
from datetime import timedelta
from datetime import datetime
import time
from nredarwin.webservice import DarwinLdbSession
import csv

darwin_sesh = DarwinLdbSession(
    wsdl="https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx",
    api_key="YOUR_API_KEY_HERE")

stationDict = {}
#Contains station names and their respective station codes

with open('stationcodes.csv') as stationcodes:
    reader = csv.reader(stationcodes)
    for row in reader:
        stationDict[(row[0].upper())] = row[1]


class station():
    def __init__(self, name, walkingTime=None, destination=None):
        # Initialises the user preferences for their station, the time it takes to get there (optional) and their line (optional)
        self.name = name
        self.walkingTime = walkingTime
        self.destination = destination

    def call(self):
        #Calls the platform board and dispays the results

        board = darwin_sesh.get_station_board(self.name)
        print(board.location_name)
Пример #19
0
import twython
import datetime
import time
import os

from auth import (consumer_key, consumer_secret, access_token,
                  access_token_secret, rttapi_username, rttapi_password,
                  nre_key)

from twython import Twython
twitter = Twython(consumer_key, consumer_secret, access_token,
                  access_token_secret)

from nredarwin.webservice import DarwinLdbSession
darwin_session = DarwinLdbSession(
    wsdl="https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx",
    api_key=nre_key)

path = os.getcwd()
tlc = os.path.basename(path).upper()
out = ""
message = ""


def setTimer():
    return 60 - (datetime.datetime.now().second +
                 datetime.datetime.now().microsecond * 0.000001)


board = darwin_session.get_station_board(tlc, rows=200)
Пример #20
0
from nredarwin.webservice import DarwinLdbSession

# initiate a session
# this depends on the DARWIN_WEBSERVICE_API_KEY environment variable
# The WSDL environment variable also allows for
darwin_session = DarwinLdbSession(wsdl='https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx?ver=2015-05-14', api_key = '6adcdf6a-2b06-40e0-8436-469c4468a679')
print("Enter 3 digit CRS code:")
try:
    input = raw_input #python2 has raw_input, python3 has input
except NameError:
    pass
crs_code = input().upper()

# retrieve departure board
board = darwin_session.get_station_board(crs_code)

# print table header
print("\nNext departures for %s" % (board.location_name))
print("""
-------------------------------------------------------------------------------
|  PLAT  | DEST                                        |   SCHED   |    DUE   |
------------------------------------------------------------------------------- """)

# Loop through services
for service in board.train_services:
    print("| %6s | %43s | %9s | %8s |" %(service.platform or "", service.destination_text, service.std, service.etd))

# Print a footer 
print("-------------------------------------------------------------------------------")