raildata

package module
v0.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 23, 2025 License: Apache-2.0 Imports: 13 Imported by: 0

README

Package raildata is a library to access NJ Transit's RailData API.

It provides automatic API token management and a higher-level, enriched API.

Library usage

import "github.com/jtarrio/raildata"

CLI tool

This repository also includes a command-line utility that uses the raildata library to download and display NJ Transit information. For more information, execute this:

go run github.com/jtarrio/raildata/raildata-cli

API access

In order to use this library, you need to visit https://developer.njtransit.com/registration/login to request your NJ Transit developer API credentials for the RailData API.

Example

// Read the token from a file
token, err := io.ReadFile("/path/to/token-file")
if err != nil { return err }
client, err := raildata.NewClient(
    // Provide the token to the client so it doesn't need to get a new one
    raildata.WithToken(string(token)),
    // Provide the username and password to the client so it can get a new token if the old one expires
    raildata.WithCredentials(username, password),
    // If the token changes, save it to the file so we can use it in the future
    raildata.WithTokenUpdateListener(func(newToken string, oldToken string) {
        _ = io.WriteFile("/path/to/token-file", []byte(newToken))
    }),
)
if err != nil { return err }

vehicles, err := client.GetVehicleData(context.Background())
if err != nil { return err }
for _, vehicle := vehicles.Vehicles {
    println(vehicle.TrainId)
}

Caveats

This client is not provided by NJ Transit. It may fail to parse some messages as we are still discovering which fields are optional and which aren't. Use at your own risk.

Documentation

Overview

Package raildata is a library to access NJ Transit's RailData API.

API token management

The RailData API requires you to create a token using your username and password, and then use that token for all operations. There is a limit to the number of tokens you can create per day, so it is essential to manage the API token properly to avoid spurious token creations.

This library takes care of token management for you. It can receive a token to use throughout the session, or it can create one by itself. It can also create a new token automatically when the old token expires. When it gets a new token, it will call a function you provide so you can save the token for later.

Enriched API

Some RailData API methods return station names, while others return short names or station codes or even "destination" names that don't match any existing station. The same happens with other types of information, like line codes or names.

This library normalizes and enriches the API results so that, whenever you have a station, you get its code and its name and its short name; whenever you have a line, you get its code and its name and its official abbreviation.

Similarly, dates and times are represented as time.Time objects, delays and dwell intervals are represented as time.Duration, true/false and yes/no values are represented as booleans, we have a special type for colors, and optional values are represented as pointers.

Rate-limited functions

Some RailData API methods can only be called 5 or 10 times per day. This library splits them out to a separate interface that you can get by calling the [Client.RateLimitedMethods] method. This makes it clear to you, the programmer, that you should try to avoid calling those methods too often.

NJ Transit developer credentials

In order to use this library, you need to visit https://developer.njtransit.com/registration/login to request your NJ Transit developer API credentials for the RailData API.

Index

Constants

This section is empty.

Variables

View Source
var Lines = []Line{
	{Code: "AC", Name: "Atlantic City Line", Abbreviation: "ACRL", Color: MustParseHtmlColor("#075AAA"), OtherAbbrs: []string{"ATLC"}},
	{Code: "MC", Name: "Montclair-Boonton Line", Abbreviation: "MOBO", Color: MustParseHtmlColor("#E66859"), OtherAbbrs: []string{"BNTN", "BNTNM", "MNBTN"}},
	{Code: "BC", Name: "Bergen County Line", Abbreviation: "BERG", Color: MustParseHtmlColor("#FFD411"), OtherAbbrs: []string{"MNBN"}},
	{Code: "ML", Name: "Main Line", Abbreviation: "MAIN", Color: MustParseHtmlColor("#FFD411"), OtherAbbrs: []string{"MNBN"}},
	{Code: "ME", Name: "Morris & Essex Line", Abbreviation: "M&E", Color: MustParseHtmlColor("#08A652"), OtherAbbrs: []string{"MNE"}},
	{Code: "GS", Name: "Gladstone Branch", Abbreviation: "M&E", Color: MustParseHtmlColor("#A4C9AA"), OtherAbbrs: []string{"MNEG"}},
	{Code: "NE", Name: "Northeast Corridor Line", Abbreviation: "NEC", Color: MustParseHtmlColor("#DD3439")},
	{Code: "NC", Name: "North Jersey Coast Line", Abbreviation: "NJCL", Color: MustParseHtmlColor("#03A3DF"), OtherAbbrs: []string{"NJCLL"}},
	{Code: "PV", Name: "Pascack Valley Line", Abbreviation: "PASC", Color: MustParseHtmlColor("#94219A")},
	{Code: "PR", Name: "Princeton Branch", Abbreviation: "PRIN", Color: MustParseHtmlColor("#DD3439")},
	{Code: "RV", Name: "Raritan Valley Line", Abbreviation: "RARV", Color: MustParseHtmlColor("#F2A537")},
	{Code: "SL", Name: "BetMGM Meadowlands", Abbreviation: "BMGM", Color: MustParseHtmlColor("#C1AA72")},
	{Code: "AM", Name: "Amtrak", Abbreviation: "AMTK", Color: MustParseHtmlColor("#FFFF00")},
	{Code: "SP", Name: "Septa", Abbreviation: "SEPTA", Color: MustParseHtmlColor("#1F4FA3")},
}

Lines contains a list of known lines.

View Source
var SpecialTracks = []SpecialTrack{
	{Id: "Single", StationCode: "ON", Translation: "1"},
	{Id: "2", StationCode: "MP", Translation: "1"},
	{Id: "B", StationCode: "UV", Translation: "2"},
	{Id: "Single", StationCode: "UV", Translation: "1"},
	{Id: "0", StationCode: "NA", Translation: "A"},
	{Id: "4", StationCode: "TS", Translation: "E"},
	{Id: "2", StationCode: "TS", Translation: "F"},
	{Id: "3", StationCode: "TS", Translation: "H"},
	{Id: "1", StationCode: "TS", Translation: "G"},
	{Id: "Single", StationCode: "ST", Translation: "S"},
}

SpecialTracks contains a list of track numbers, as provided by the API, that are different in the real world. For example, track "Single" in station "UV" is seen as track "1" in the real world.

View Source
var StationPositions = []StationPosition{
	{Code: "0", Description: "First station"},
	{Code: "1", Description: "Intermediate station"},
	{Code: "2", Description: "Final station"},
}

StationPositions contains a list of valid station positions.

View Source
var Stations = []Station{}/* 176 elements not displayed */
View Source
var StopCodes = []StopCode{
	{Code: "A", Description: "Arrival time"},
	{Code: "S", Description: "Normal Stop"},
	{Code: "S*", Description: "Normal stop. May leave up to 3 minutes early"},
	{Code: "LV", Description: "Leaves 1 minute after scheduled time"},
	{Code: "L", Description: "Train can leave before scheduled departure. Will hold for connections"},
	{Code: "H", Description: "Will hold for connection unless authorize by dispatcher"},
	{Code: "D", Description: "Stop to discharge passengers only. May leave ahead of schedule"},
	{Code: "R", Description: "Stop to receive passengers only"},
	{Code: "R*", Description: "Stop to receive passengers only. May leave 3 minutes early"},
	{Code: "E", Description: "Employee stop. May leave ahead of schedule"},
}

StopCodes contains a list of valid stop codes.

View Source
var TrainIdPrefixes = []TrainIdPrefix{
	{Prefix: "A", Description: "Amtrak Train"},
	{Prefix: "S", Description: "Septa Train"},
	{Prefix: "X", Description: "Non-Revenue train - Does not accept passengers"},
}

TrainIdPrefixes contains the list of special train number prefixes.

Functions

func TranslateTrackNumber

func TranslateTrackNumber(trackId string, stationCode StationCode) string

TranslateTrackNumber takes a track id and a station code and returns the track name used in the real world.

Types

type Client

type Client interface {
	// GetToken returns the token currently being used by the client.
	GetToken() string
	// GetStationList returns a list of all stations, with their codes, names, and short names.
	GetStationList(context.Context) (*GetStationListResponse, error)
	// GetStationMsg returns a list of messages and alerts, optionally scoped to one station and/or one line.
	GetStationMsg(context.Context, *GetStationMsgRequest) (*GetStationMsgResponse, error)
	// GetTrainSchedule returns the schedule for the next 19 trains departing from a station.
	//
	// This method also returns information about each train's stops.
	GetTrainSchedule(context.Context, *GetTrainScheduleRequest) (*GetTrainScheduleResponse, error)
	// GetTrainSchedule19Records returns the schedule for the next 19 trains departing from a station,
	// optionally scoped to one line.
	//
	// This method does not return information about each train's stops. You can use GetTrainStopList to retrieve it.
	GetTrainSchedule19Records(context.Context, *GetTrainSchedule19RecordsRequest) (*GetTrainScheduleResponse, error)
	// GetTrainStopList returns the list of stops for a train.
	// Returns nil if the provided train id is not valid.
	GetTrainStopList(context.Context, *GetTrainStopListRequest) (*GetTrainStopListResponse, error)
	// GetVehicleData returns the position and status for all active trains.
	//
	// A train appears in this list if it has moved in the last 5 minutes.
	GetVehicleData(context.Context) (*GetVehicleDataResponse, error)
	// RateLimitedMethods returns an interface for rate-limited operations.
	RateLimitedMethods() RateLimitedMethods
}

Client is the interface you use to access the RailData server.

func NewClient

func NewClient(options ...Option) (Client, error)

NewClient creates a client for the RailData API.

The RailData API uses a token to access all the operations, so you need to pass one or more options to provide either the token or the credentials to use to generate this token.

Note that you can only generate 5 tokens per day, so we highly recommend to save the current token so you can pass it in the next call to NewClient.

Example:

// Read the token from a file
token, err := io.ReadFile("/path/to/token-file")
if err != nil { return err }
client, err := raildata.NewClient(
	// Provide the token to the client so it doesn't need to get a new one
	raildata.WithToken(string(token)),
	// Provide the username and password to the client so it can get a new token if the old one expires
	raildata.WithCredentials(username, password),
	// If the token changes, save it to the file so we can use it in the future
	raildata.WithTokenUpdateListener(func(newToken string, oldToken string) {
		_ = io.WriteFile("/path/to/token-file", []byte(newToken))
	}),
)

type Color

type Color struct {
	// contains filtered or unexported fields
}

Color contains a color specification to render a line name.

func MustParseHtmlColor added in v0.0.2

func MustParseHtmlColor(s string) Color

MustParseHtmlColor parses the HTML color specification or panics if there was an error.

func NewColor

func NewColor(r, g, b int) (Color, error)

NewColor returns a Color object given its red, green, and blue components (from 0 to 255).

func ParseHtmlColor

func ParseHtmlColor(s string) (Color, error)

ParseHtmlColor parses an HTML color specification into a Color object.

func (Color) Html

func (c Color) Html() string

Html returns an HTML color specification for this color.

func (Color) RGB

func (c Color) RGB() (r, g, b int)

RGB returns the red, green, and blue components of this color (from 0 to 255).

type ColorSet

type ColorSet struct {
	// Foreground contains the color for the text.
	Foreground Color
	// Background contains the color for the background.
	Background Color
	// Shadow contains the color for the text's shadow.
	Shadow Color
}

ColorSet contains colors used to render a line name.

type Direction

type Direction int

Direction represents the direction of travel of a trip.

const (
	DirectionEastbound Direction = iota // eastbound.
	DirectionWestbound                  // westbound.
)

type Finder

type Finder[T any, C ~string] interface {
	// Sets up to find an object with the given code.
	WithCode(code C) Finder[T, C]
	// Sets up to find an object with the given name.
	WithName(name string) Finder[T, C]
	// Searches for the object, returning either (non-nil pointer, true) if found,
	// or (nil pointer, false) if not found.
	Search() (*T, bool)
	// Searches for the object, returning either the found object, or a made-up
	// object that was built from the search data.
	SearchOrSynthesize() *T
}

Finder is an interface to find objects of type T with codes of type C.

type GetStationListResponse

type GetStationListResponse struct {
	// Stations contains the list of stations.
	Stations []Station
}

GetStationListResponse contains the result of the GetStationList method.

func ParseGetStationsList

func ParseGetStationsList(input []api.GetStations) (*GetStationListResponse, error)

type GetStationMsgRequest

type GetStationMsgRequest struct {
	// StationCode contains an optional station to filter the messages on.
	StationCode *StationCode
	// LineCode contains an optional line to filter the messages on.
	LineCode *LineCode
}

GetStationMsgRequest contains the arguments of the GetStationMsg method.

type GetStationMsgResponse

type GetStationMsgResponse struct {
	// Messages contains the list of messages.
	Messages []StationMsg
}

GetStationMsgResponse contains the result of the GetStationMsg method.

func ParseStationMsgsList

func ParseStationMsgsList(input []api.StationMsgs) *GetStationMsgResponse

type GetStationScheduleRequest

type GetStationScheduleRequest struct {
	// StationCode contains the station to get the schedule for.
	StationCode StationCode
	// NjtOnly contains whether only NJ Transit trains should be returned.
	// If false, the results may also contain Amtrak trains.
	NjtOnly bool
}

GetStationScheduleRequest contains the arguments of the GetStationSchedule method.

type GetStationScheduleResponse

type GetStationScheduleResponse struct {
	// Entries contains the schedule entries.
	Entries []StationSchedule
}

GetStationScheduleResponse contains the result of the GetStationSchedule method.

func ParseDailyStationInfoList

func ParseDailyStationInfoList(input []api.DailyStationInfo) (*GetStationScheduleResponse, error)

type GetTrainSchedule19RecordsRequest

type GetTrainSchedule19RecordsRequest struct {
	// StationCode contains the station to get the schedule for.
	StationCode StationCode
	// LineCode contains an optional line to filter the schedule on.
	LineCode *LineCode
}

GetTrainSchedule19RecordsRequest contains the arguments of the GetTrainSchedule19Records method.

type GetTrainScheduleRequest

type GetTrainScheduleRequest struct {
	// StationCode contains the station to get the schedule for.
	StationCode StationCode
}

GetTrainScheduleRequest contains the arguments of the GetTrainSchedule method.

type GetTrainScheduleResponse

type GetTrainScheduleResponse struct {
	// Station contains the station this schedule belongs to.
	Station Station
	// Messages contains a list of messages for this station.
	Messages []StationMsg
	// Entries contains the schedule entries.
	Entries []TrainScheduleEntry
}

GetTrainScheduleResponse contains the result of the GetTrainSchedule and GetTrainSchedule19Records methods.

func ParseStationInfo

func ParseStationInfo(input *api.StationInfo) *GetTrainScheduleResponse

type GetTrainStopListRequest

type GetTrainStopListRequest struct {
	// TrainId contains the train whose list of stops needs to be returned.
	TrainId string
}

GetTrainStopListRequest contains the arguments of the GetTrainStopList method.

type GetTrainStopListResponse

type GetTrainStopListResponse struct {
	// TrainId contains the train this information belongs to.
	TrainId string
	// Line contains the line this train runs on.
	Line Line
	// Color contains the colors used to render the line name.
	Color ColorSet
	// Destination contains the destination name.
	Destination string
	// DestinationStation contains the destination station, if it could be determined from the destination name.
	DestinationStation *Station
	// TransferAt contains the name of a transfer station. Used for Long Branch connections to Bayhead.
	TransferAt *string
	// Stops contains the list of stops for this train.
	Stops []TrainStop
	// Capacity contains information on how full this train is.
	Capacity []TrainCapacity
}

GetTrainStopListResponse contains the result of the GetTrainStopList method.

func ParseStops

func ParseStops(input *api.Stops) *GetTrainStopListResponse

type GetVehicleDataResponse

type GetVehicleDataResponse struct {
	// Vehicles contains a list of active trains.
	Vehicles []VehicleData
}

GetVehicleDataResponse contains the result of the GetVehicleData method.

func ParseVehicleDataInfoList

func ParseVehicleDataInfoList(input []api.VehicleDataInfo) *GetVehicleDataResponse

type IsValidTokenResponse

type IsValidTokenResponse struct {
	// ValidToken contains whether the token is valid.
	ValidToken bool
	// UserId contains the user id for this token, if found.
	UserId *string
}

IsValidTokenResponse contains the result of the IsValidToken method.

func ParseValidTokenResponse

func ParseValidTokenResponse(input *api.ValidTokenResponse) (*IsValidTokenResponse, error)

type Line

type Line struct {
	// Code contains the line's 2-letter code.
	Code LineCode
	// Name contains the line's full name.
	Name string
	// Abbreviation contains a 3-5 letter abbreviation of the line's name.
	Abbreviation string
	// Color contains the color for this line.
	Color Color
	// OtherAbbrs contains a list with alternative abbreviations for this line.
	OtherAbbrs []string
}

Line contains information about a line.

type LineCode

type LineCode string

LineCode is a 2-letter identifier for a line.

type LineFinder

type LineFinder = Finder[Line, LineCode]

LineFinder is an object to find lines by code or name.

func FindLine

func FindLine() LineFinder

FindLine returns an object that lets you find a line by code or name. If no exact match is found and the name was specified, this function uses fuzzy search to find the closest match.

The [LineFinder.SearchOrSynthesize] method will, if it doesn't find a suitable line, return a synthesized Line object that uses the provided search data. If no code was specified, "XX" will be used in its place. If no name was specified, "Unknown [line code]" will be used in its place, and "XX" followed by the line code will be used in place of the line abbreviation.

type Location

type Location struct {
	// Longitude contains the vehicle's longitude, in degrees East.
	Longitude float64
	// Latitude contains the vehicle's latitude, in degrees North.
	Latitude float64
}

Location contains a vehicle's GPS location.

type MsgType

type MsgType int

MsgType represents the type of a message.

const (
	MsgTypeBanner     MsgType = iota // a "banner" style message, displayed along other information.
	MsgTypeFullScreen                // a message that takes over the screen.
)

type Option

type Option func(*raildataClient)

func WithApiBase

func WithApiBase(apiBase url.URL) Option

WithApiBase sets the API endpoint's base URL to the specified value.

func WithCredentials

func WithCredentials(username string, password string) Option

WithCredentials sets the username and password so the client can get a new token if the old one is invalid or expires.

func WithHttpClient

func WithHttpClient(client *http.Client) Option

WithHttpClient sets the HTTP client to use.

func WithTestEndpoint

func WithTestEndpoint(testEndpoint bool) Option

WithTestEndpoint sets the API endpoint to the test endpoint (if true) or the production endpoint (if false).

func WithToken

func WithToken(token string) Option

WithToken sets the initial token to use.

func WithTokenUpdateListener

func WithTokenUpdateListener(listener TokenUpdateListener) Option

WithTokenUpdateListener registers a function that is called whenever the client creates a new token.

type RateLimitedMethods

type RateLimitedMethods interface {
	// IsValidToken returns whether the current token is valid, and the user name associated with it.
	//
	// Note that NJ Transit sets a limit of 10 calls per day to this endpoint, so don't use it indiscriminately.
	// An alternative is to call GetStationList or GetStationMsg, which will return a result if the token is valid
	// (and will try to autoupdate it if necessary.)
	IsValidToken(context.Context) (*IsValidTokenResponse, error)
	// GetStationSchedule returns the schedule for the next 27 hours for one station.
	//
	// There is a limit of 5 calls per day and, even though the documentation claims you can get a full
	// schedule for all stations omitting the StationCode parameter, it is not true, so you should avoid
	// using this method.
	GetStationSchedule(context.Context, *GetStationScheduleRequest) (*GetStationScheduleResponse, error)
}

RateLimitedMethods contains methods you can only call a few times per day.

type ScheduleEntry

type ScheduleEntry struct {
	// DepartureTime contains the scheduled departure date/time for the train.
	DepartureTime time.Time
	// Destination contains the destination name.
	Destination string
	// DestinationStation contains the destination station, if it could be determined from the destination name.
	DestinationStation *Station
	// Line contains the line this train runs on.
	Line Line
	// TrainId contains the train's number.
	TrainId string
	// ConnectingTrainId contains the connecting train's number. Used for Long Branch connections to Bayhead.
	ConnectingTrainId *string
	// StationPosition contains this station's position along the trip.
	StationPosition StationPosition
	// Direction contains the direction of travel.
	Direction Direction
	// DwellTime contains how long the train will wait at the station.
	DwellTime *time.Duration
	// PickupOnly indicates, if true, that the train will only pick up (not discharge) passengers at this stop.
	PickupOnly bool
	// DropoffOnly indicates, if true, that the train will only discharge (not pick up) passengers at this stop.
	DropoffOnly bool
	// StopCode contains a stop code for this station.
	StopCode *StopCode
}

ScheduleEntry contains an entry in a station's schedule.

func ParseDailyScheduleInfo

func ParseDailyScheduleInfo(input *api.DailyScheduleInfo) *ScheduleEntry

type SectionPosition

type SectionPosition int

SectionPosition designates a section in a train.

const (
	SectionPositionFront  SectionPosition = iota // the first cars in a train.
	SectionPositionMiddle                        // the middle cars in a train.
	SectionPositionBack                          // the last cars in a train.
)

type SpecialTrack

type SpecialTrack struct {
	Id          string
	StationCode StationCode
	Translation string
}

SpecialTrack contains API-to-real-world track number translation data for certain stations.

type Station

type Station struct {
	// Code contains the station's 2-letter code.
	Code StationCode
	// Name contains the station's full name.
	Name string
	// ShortName contains a shorter version of the station's name.
	ShortName string
}

Station contains information about a station.

func ParseGetStations

func ParseGetStations(input *api.GetStations) *Station

type StationCode

type StationCode string

StationCode is a 2-letter identifier for a station.

type StationFinder

type StationFinder = Finder[Station, StationCode]

StationFinder is an object to find stations by code or name.

func FindStation

func FindStation() StationFinder

FindStations returns an object that lets you find a station by code or name. If no exact match is found and the name was specified, this function uses fuzzy search to find the closest match.

The [StationFinder.SearchOrSynthesize] method will, if it doesn't find a suitable station, return a synthesized Station object that uses the provided search data. If no code was specified, "XX" will be used in its place. If no name was specified, "Unknown [station code]" will be used in its place, and a shortened version of the name will be used in place of the line abbreviation.

type StationMsg

type StationMsg struct {
	// Type contains the type of message.
	Type MsgType
	// Text contains the message's text. It may contain HTML code and escape sequences.
	Text string
	// PubDate indicates when the message was published.
	PubDate time.Time
	// Id contains an identifier for the message. Typically only used with messages from third-party feeds.
	Id *string
	// Agency identifies the agency that published the message: NJT, AMT, or none.
	Agency *string
	// Source identifies the source of the message: RSS_NJTRailAlerts or none.
	Source *string
	// StationScope contains a list of stations this message pertains to.
	StationScope []Station
	// LineScope contains a list of lines this message pertains to.
	LineScope []Line
}

StationMsg contains a message or alert.

func ParseStationMsgs

func ParseStationMsgs(input *api.StationMsgs) *StationMsg

type StationPosition

type StationPosition struct {
	Code        string
	Description string
}

StationPosition contains data about a station's position in relation to a route.

func GetStationPosition

func GetStationPosition(code string) StationPosition

GetStationPosition returns the StationPosition for the given code, or a made-up object for an unknown code.

type StationSchedule

type StationSchedule struct {
	// Station identifies the station this schedule belongs to.
	Station *Station
	// Entries contains a list of schedule entries.
	Entries []ScheduleEntry
}

StationSchedule contains a station's 27-hour schedule.

func ParseDailyStationInfo

func ParseDailyStationInfo(input *api.DailyStationInfo) *StationSchedule

type StopCode

type StopCode struct {
	Code        string
	Description string
}

StopCode contains information about a train's behavior at a station

func GetStopCode

func GetStopCode(code string) StopCode

GetStopCode returns the StopCode for a given code, or a made-up object for an unknown code.

type StopLine

type StopLine struct {
	// Line contain's the line that connects at this stop.
	Line Line
	// Color contains a color used to represent the line.
	Color Color
}

StopLine contains information about a connecting line.

func ParseStopLines

func ParseStopLines(input *api.StopLines) *StopLine

type TokenUpdateListener

type TokenUpdateListener func(newToken string, previousToken string)

TokenUpdateListener is the type of a function that is called whenever the client creates a new token. This function is called with the new and old token so you can ensure that the correct token is always saved even if there are many simultaneous token changes.

type TrainCapacity

type TrainCapacity struct {
	// Number contains the train's number.
	Number string
	// Location contains the train's last known position.
	Location Location
	// CreatedTime contains the time this record was creted.
	CreatedTime time.Time
	// Type contains the vehicle type.
	Type string
	// CapacityPercent contains the percentage of capacity used.
	CapacityPercent int
	// CapacityColor contains a color that represents how full the train is.
	CapacityColor Color
	// PassengerCount contains the number of passengers on board the train.
	PassengerCount int
	// Sections contains capacity information for each train section.
	Sections []TrainSection
}

TrainCapacity contains information on how full a train is.

func ParseCapacityList

func ParseCapacityList(input *api.CapacityList) *TrainCapacity

type TrainCar

type TrainCar struct {
	// TrainId contains the train car's number.
	TrainId string
	// Position contains the car's position on the train, 1 being the front.
	Position int
	// Restroom contains whether this car has a restroom.
	Restroom bool
	// CapacityPercent contains the percentage of capacity used.
	CapacityPercent int
	// CapacityColor contains a color that represents how full the car is.
	CapacityColor Color
	// PassengerCount contains the number of passengers on board the car.
	PassengerCount int
}

TrainCar contains information on how full a train car is.

func ParseCarList

func ParseCarList(input *api.CarList) *TrainCar

type TrainIdPrefix

type TrainIdPrefix struct {
	Prefix      string
	Description string
}

TrainIdPrefix contains the code and the meaning of a special train number prefix.

type TrainScheduleEntry

type TrainScheduleEntry struct {
	// DepartureTime contains the scheduled departure date/time for the train.
	DepartureTime time.Time
	// Destination contains the destination name.
	Destination string
	// Track contains the name of the track this train will leave from, if known.
	Track *string
	// Line contains the line this train runs on.
	Line Line
	// LineName contains the display name for the line. For example, the [Line] may be Amtrak, but [LineName] may contain "Acela Express".
	LineName string
	// TrainId contains the train's number.
	TrainId string
	// ConnectingTrainId contains the connecting train's number. Used for Long Branch connections to Bayhead.
	ConnectingTrainId *string
	// Status contains the train's current status.
	Status *string
	// Delay contains the train's current delay.
	Delay *time.Duration
	// LastUpdated contains the date/time this entry was updated.
	LastUpdated *time.Time
	// Color contains the colors used to render the line name.
	Color ColorSet
	// GpsLocation contains the train's last known position.
	GpsLocation *Location
	// GpsTime contains the date/time the GpsLocation was captured.
	GpsTime *time.Time
	// StationPosition contains this station's position along the trip.
	StationPosition StationPosition
	// InlineMessage contains an in-line message for the train at the station.
	InlineMessage *string
	// Capacity contains information on how full this train is.
	Capacity []TrainCapacity
	// Stops contains the list of stops for this train.
	Stops []TrainStop
}

TrainScheduleEntry contains an entry in a train's schedule at a station.

func ParseScheduleInfo

func ParseScheduleInfo(input *api.ScheduleInfo, station *Station) *TrainScheduleEntry

type TrainSection

type TrainSection struct {
	// Position contains the section's position on the train.
	Position SectionPosition
	// CapacityPercent contains the percentage of capacity used.
	CapacityPercent int
	// CapacityColor contains a color that represents how full the section is.
	CapacityColor Color
	// PassengerCount contains the number of passengers on board the section.
	PassengerCount int
	// Cars contains capacity information for each car in this section.
	Cars []TrainCar
}

TrainSection contains information on how full a train section is.

func ParseSectionList

func ParseSectionList(input *api.SectionList) *TrainSection

type TrainStop

type TrainStop struct {
	// Station contains the station where this train stops.
	Station Station
	// ArrivalTime contains the expected arrival time.
	ArrivalTime *time.Time
	// PickupOnly indicates, if true, that the train will only pick up (not discharge) passengers at this stop.
	PickupOnly bool
	// DropoffOnly indicates, if true, that the train will only discharge (not pick up) passengers at this stop.
	DropoffOnly bool
	// Departed indicates, if true, that the train has already left this station.
	Departed bool
	// StopStatus contains an optional status at the stop: OnTime, Delayed, Cancelled, or none.
	StopStatus *string
	// DepartureTime contains the expected departure time.
	DepartureTime *time.Time
	// StopLines contains a list of lines that connect at this stop.
	StopLines []StopLine
}

TrainStop contains information about a train's stop.

func ParseStopList

func ParseStopList(input *api.StopList) *TrainStop

type VehicleData

type VehicleData struct {
	// TrainId contains the train's number.
	TrainId string
	// Line contains the line this train is running on.
	Line Line
	// Direction contains this train's direction of travel.
	Direction Direction
	// TrackCircuitId contains the last identified circuit id for this train.
	TrackCircuitId string
	// LastUpdated contains the time this information was last refreshed.
	LastUpdated time.Time
	// DepartureTime contains the expected departure time at the next station.
	DepartureTime time.Time
	// Delay contains the train's current delay.
	Delay *time.Duration
	// NextStop contains the train's next stop.
	NextStop *Station
	// Location contains the train's GPS location.
	Location *Location
}

VehicleData contains innformation about an active train.

func ParseVehicleDataInfo

func ParseVehicleDataInfo(input *api.VehicleDataInfo) *VehicleData

Directories

Path Synopsis
Package api provides low-level functions to access the RailData API.
Package api provides low-level functions to access the RailData API.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL