Documentation ¶
Overview ¶
admin provides an event-driven interface to the Admin port of an OpenTTD game server. You probably want to use this library if you're making bots, or just want raw access to the packet data.
Index ¶
- Constants
- Variables
- type Banned
- type Chat
- type Client
- type ClientError
- type ClientInfo
- type ClientJoin
- type ClientQuit
- type ClientUpdate
- type CmdLogging
- type CmdNames
- type Company
- type CompanyEconomy
- type CompanyInfo
- type CompanyNew
- type CompanyRemove
- type CompanyStats
- type CompanyUpdate
- type Connect
- type Console
- type Date
- type Disconnect
- type Error
- type Event
- type EventHandler
- type EventInterfaceProvider
- type Full
- type Gamescript
- type Newgame
- type Pong
- type Protocol
- type Rcon
- type RconEnd
- type Session
- func (s *Session) AddHandler(handler interface{}) func()
- func (s *Session) AddHandlerOnce(handler interface{}) func()
- func (s *Session) Chat(act enum.Action, dest enum.Destination, destID uint32, message string) (err error)
- func (s *Session) Close() (err error)
- func (s *Session) GamescriptCommand(json string) (err error)
- func (s *Session) HeartbeatLatency() time.Duration
- func (s *Session) Open() error
- func (s *Session) Poll(t enum.UpdateType, id uint32) (err error)
- func (s *Session) Rcon(command string) (err error)
- func (s *Session) RconSync(command string) (ret []Rcon, err error)
- func (s *Session) RequestUpdates(t enum.UpdateType, f enum.UpdateFrequency) (err error)
- type Shutdown
- type State
- type Welcome
Constants ¶
const ( // LogError level is used for critical errors that could lead to data loss // or panic that would not be returned to a calling function. LogError int = iota // LogWarning level is used for very abnormal events and errors that are // also returned to a calling function. LogWarning // LogInformational level is used for normal non-error activity LogInformational // LogDebug level is for very detailed non-error activity. This is // very spammy and will impact performance. LogDebug )
const FailedPongs = 6
FailedPongs is the Number of pong intervals to wait until forcing a connection restart.
const VERSION = "0.1.0"
VERSION of Gopenttd, follows Semantic Versioning. (http://semver.org/)
Variables ¶
var ErrAlreadyConnected = errors.New("admin connection already open")
var ErrInvalidUpdateFrequency = errors.New("given update frequency is not valid")
var ErrNilState = errors.New("state not instantiated, please use admin.New() or assign Session.State")
ErrNilState is returned when the state is nil.
var ErrServerBanned = errors.New("banned from server")
var ErrServerError = errors.New("server encountered an error")
var ErrServerFull = errors.New("server is full")
var ErrStateNotFound = errors.New("state cache not found")
ErrStateNotFound is returned when the state cache requested is not found
var Logger func(msgL, caller int, format string, a ...interface{})
Logger can be used to replace the standard logging for gopenttd
Functions ¶
This section is empty.
Types ¶
type Chat ¶ added in v0.0.2
type Chat struct { Action uint8 // Action such as NETWORK_ACTION_CHAT_CLIENT (see #NetworkAction). Destination uint8 // Destination type such as DESTTYPE_BROADCAST (see #DestType). ID uint32 // ID of the client who sent this message. Message string // Message. Money uint64 // Money (only when it is a 'give money' action). }
Chat fires when any new chat message is posted.
type Client ¶ added in v0.0.2
type Client struct { // The client nickname. Name string `json:"name"` // The client's IP address. // This can be nil if the client is the host or is connecting via an invalid address, so watch out! Address net.IP `json:"address"` // The language the client is declaring themselves as. Language util.OpenttdLanguage `json:"language"` // The date the client joined the game. // This is set to zero if the client is the server host, so watch out! JoinDate time.Time `json:"date_join"` // The ID of the company that the client is playing in (set to 255 for spectators) Company uint8 `json:"company"` }
type ClientError ¶ added in v0.0.2
type ClientError struct { ID uint32 // ID of the client throwing the error. Error enum.NetError // Error the client made (see NetworkErrorCode). }
ClientError fires when a client experiences an error (usually causes them to quit).
type ClientInfo ¶ added in v0.0.2
type ClientInfo struct { ID uint32 // ID of the client. Address string // Network address of the client. (Can be nil if they're the host) Name string // Name of the client. Language uint8 // Language of the client. JoinDate uint32 // Date the client joined the game. (Can be nil if they're the host) Company uint8 // ID of the company the client is playing as (255 for spectators). }
ClientInfo fires when information is provided for a client (usually polled).
type ClientJoin ¶ added in v0.0.2
type ClientJoin struct {
ID uint32 // ID of the new client.
}
ClientJoin fires when a client joins.
type ClientQuit ¶ added in v0.0.2
type ClientQuit struct {
ID uint32 // ID of the leaving client.
}
ClientQuit fires when a client leaves the game.
type ClientUpdate ¶ added in v0.0.2
type ClientUpdate struct { ID uint32 // ID of the client. Name string // Name of the client. Company uint8 // ID of the company the client is playing as (255 for spectators). }
ClientUpdate fires when a client changes the company it is playing as, or its name.
type CmdLogging ¶ added in v0.0.2
type CmdLogging struct { Client uint32 // ID of the client sending the command. Company uint8 // ID of the company (0..MAX_COMPANIES-1). CommandID uint16 // ID of the command. V1 uint32 // P1 (variable data passed to the command). V2 uint32 // P2 (variable data passed to the command). Tile uint32 // Tile where this is taking place. Message string // Text passed to the command. Frame uint32 // Frame of execution. }
CmdLogging is an entry of some kind of game event that occurred. Very useful for auditing. You usually need realtime updates to get these.
type CmdNames ¶ added in v0.0.2
type CmdNames struct { /* * NOTICE: Pack provided with this packet is not stable and will not be * treated as such. Do not rely on IDs or names to be constant * across different versions / revisions of OpenTTD. * Pack provided in this packet is for logging purposes only. */ Commands map[uint16]string // Map of the ID of the DoCommand with the name of it. }
CmdNames is a response to a request for command names. You probably shouldn't track this event - use the state on the session.
type Company ¶ added in v0.0.2
type Company struct { // The company name. Name string `json:"name"` // The manager of the company (client-defined, not definitively the name of a client - it appears under the portrait). Manager string `json:"manager"` // The colour representing this company in-game. Colour helpers.OpenttdColour `json:"colour"` // The year the company was first founded. YearStart uint32 `json:"start_year"` // The value of the company, in credits. Value uint64 `json:"value"` // The amount of disposable cash the company has. Money uint64 `json:"cash"` // The company's current income. Can go negative if they're making a loss. Income int64 `json:"income"` // The company's current loan. Loan uint64 `json:"loan"` // The number of quarters this company has been in a bankruptcy state (this may mean they're about to be dissolved!) Bankruptcy uint8 `json:"bankruptcy"` // Share 1 is owned by... Share1 uint8 `json:"share1"` Share2 uint8 `json:"share2"` Share3 uint8 `json:"share3"` Share4 uint8 `json:"share4"` // Cargo delivered in the current quarter. CargoThisQuarter uint16 `json:"cargo_current"` // Cargo delivered in the last full quarter. CargoLastQuarter uint16 `json:"cargo_last"` // Cargo delivered in the quarter before the last full one. CargoPreviousQuarter uint16 `json:"cargo_previous"` // Company value in the last quarter. ValueLastQuarter uint64 `json:"value_last"` // Company value in the previous quarter. ValuePreviousQuarter uint64 `json:"value_previous"` // Company performance index in the last quarter, out of 1000. PerformanceLastQuarter uint16 `json:"performance_last"` // Company performance index in the previous quarter. PerformancePreviousQuarter uint16 `json:"performance_previous"` // Whether the company has a password set. Passworded bool `json:"is_passworded"` // Whether the company is controlled by an AI. AI bool `json:"is_ai"` // A count of the vehicles and stations the company has. Vehicles util.OpenttdTypeCounts `json:"vehicle_count"` Stations util.OpenttdTypeCounts `json:"station_count"` }
type CompanyEconomy ¶ added in v0.0.2
type CompanyEconomy struct { ID uint8 // ID of the company. Money uint64 // Money (cash in hand). Loan uint64 // Loan. Income int64 // Income. CargoThisQuarter uint16 // Delivered cargo (this quarter). ValueLastQuarter uint64 // Company value (last quarter). PerformanceLastQuarter uint16 // Performance (last quarter). CargoLastQuarter uint16 // Delivered cargo (last quarter). ValuePreviousQuarter uint64 // Company value (previous quarter). PerformancePreviousQuarter uint16 // Performance (previous quarter). CargoPreviousQuarter uint16 // Delivered cargo (previous quarter). }
CompanyEconomy fires when new economical data for the company is available (either polled or regularly, depends what you signed up for)
type CompanyInfo ¶ added in v0.0.2
type CompanyInfo struct { ID uint8 // ID of the company. Name string // Name of the company. Manager string // Name of the companies manager. Colour uint8 // Main company colour. Password bool // Company is password protected. StartDate uint32 // Year the company was inaugurated. IsAI bool // Company is an AI. }
CompanyInfo fires when information for a company is provided (usually polled).
type CompanyNew ¶ added in v0.0.2
type CompanyNew struct {
ID uint8 // ID of the new company.
}
CompanyNew fires when a new company is founded.
type CompanyRemove ¶ added in v0.0.2
type CompanyRemove struct { ID uint8 // ID of the company. Reason enum.CompanyRemoveReason // Reason for being removed. }
CompanyRemove fires when a company is removed from the game.
type CompanyStats ¶ added in v0.0.2
type CompanyStats struct { ID uint8 // ID of the company. Trains uint16 // Number of trains. Lorries uint16 // Number of lorries. Buses uint16 // Number of busses. Planes uint16 // Number of planes. Ships uint16 // Number of ships. TrainStations uint16 // Number of train stations. LorryStations uint16 // Number of lorry stations. BusStops uint16 // Number of bus stops. Airports uint16 // Number of airports and heliports. Harbours uint16 // Number of harbours. }
CompanyStats fires when new statistics for the company are available (either polled or regularly, depends what you signed up for)
type CompanyUpdate ¶ added in v0.0.2
type CompanyUpdate struct { ID uint8 // ID of the company. Name string // Name of the company. Manager string // Name of the company's manager. Colour uint8 // Main company colour. Password bool // Company is password protected. BankruptcyQuarters uint8 // Quarters of Bankruptcy. }
CompanyUpdate fires when a company changes something about its metadata, such as its name.
type Connect ¶ added in v0.0.2
type Connect struct{}
Connect is the data for a Connect event. This is a synthetic event and is not dispatched by OpenTTD.
type Console ¶ added in v0.0.2
type Console struct { Origin string // The origin of the text, e.g. "console" for console, or "net" for network related (debug) messages. Message string // Text as found on the console of the server. }
Console fires when a console message is printed to the server output.
type Date ¶ added in v0.0.2
type Date struct {
CurrentDate uint32 // Current game date.
}
Date fires when the game provides an update to the current game date.
type Disconnect ¶ added in v0.0.2
type Disconnect struct{}
Disconnect is the data for a Disconnect event. This is a synthetic event and is not dispatched by OpenTTD.
type Event ¶ added in v0.0.2
type Event struct { Type uint8 `json:"t"` RawData []byte `json:"d"` // Struct contains one of the other types in this file. Struct interface{} `json:"-"` }
Event provides a basic initial struct for all game events.
type EventHandler ¶ added in v0.0.2
type EventHandler interface { // Type returns the type of event this handler belongs to. Type() uint8 // Handle is called whenever an event of Type() happens. // It is the receivers responsibility to type assert that the interface // is the expected struct. Handle(*Session, interface{}) }
EventHandler is an interface for OpenTTD events.
type EventInterfaceProvider ¶ added in v0.0.2
type EventInterfaceProvider interface { // Type is the type of event this handler belongs to. Type() uint8 // New returns a new instance of the struct this event handler handles. // This is called once per event. // The struct is provided to all handlers of the same Type(). New() interface{} }
EventInterfaceProvider is an interface for providing empty interfaces for OpenTTD events.
type Gamescript ¶ added in v0.0.2
type Gamescript struct { // Pack on this isn't available in the source? Making an assumption. Json string // JSON string from the GameScript. }
Gamescript is some data that was sent by a GameScript running on the server.
type Pong ¶ added in v0.0.2
type Pong struct {
Token uint32 // Integer value requested in the Ping.
}
Pong is sent in response to a Ping request. Probably no need to track this one; gopenttd will handle ping/pong and timeouts for you.
type Rcon ¶ added in v0.0.2
type Rcon struct { Colour uint16 // Colour as it would be used on the server or a client. Output string // Output of the executed command. }
Rcon fires when a line of RCON output from the server is returned. Use in conjunction with RconEnd to determine when a command has finished.
type RconEnd ¶ added in v0.0.2
type RconEnd struct {
Command string // The command as requested by the admin connection.
}
RconEnd denotes that the given command finished.
type Session ¶ added in v0.0.2
type Session struct { sync.RWMutex // Hostname to connect to. Hostname string // Port to connect to (note this is the admin port, usually 3977: not the game port!) Port int // Authentication token for this session Password string // Debug for printing JSON request/responses LogLevel int // Should the session reconnect on errors. ShouldReconnectOnError bool // Should state tracking be enabled. // State tracking automatically updates the State object // when events occur - if you're purely writing real time stuff, // you can turn this off. StateEnabled bool // Whether or not to call event handlers synchronously. // e.g false = launch event handlers in their own goroutines. SyncEvents bool // Whether the connection is ready Ready bool // Managed state object, updated internally with events when // StateEnabled is true. State *State // Cache of requested update frequencies - these will be // automatically sent to the server if reconnection is required. UpdateFrequencies map[enum.UpdateType]enum.UpdateFrequency // The user agent UserAgent string // Stores the last Pong that was recieved (in UTC) LastPong time.Time // Stores the last Heartbeat sent (in UTC) LastPing time.Time // contains filtered or unexported fields }
A Session represents a connection to the OpenTTD Admin protocol.
func New ¶ added in v0.0.2
New creates a new OpenTTD Admin session and will automate some startup tasks if given enough information to do so. Currently you can pass zero arguments and it will return an empty session.
func (*Session) AddHandler ¶ added in v0.0.2
func (s *Session) AddHandler(handler interface{}) func()
AddHandler allows you to add an event handler that will be fired anytime the event that matches the function fires. The first parameter is a *Session, and the second parameter is a pointer to a struct corresponding to the event for which you want to listen.
eg:
Session.AddHandler(func(s *admin.Session, m *admin.MessageCreate) { })
or:
Session.AddHandler(func(s *admin.Session, m *admin.PresenceUpdate) { })
List of events can be found at this page, with corresponding names in the library for each event: https://github.com/OpenTTD/OpenTTD/blob/master/src/network/core/tcp_admin.h There are also synthetic events fired by the library internally which are available for handling, like Connect, Disconnect, and RateLimit.
The return value of this method is a function, that when called will remove the event handler.
func (*Session) AddHandlerOnce ¶ added in v0.0.2
func (s *Session) AddHandlerOnce(handler interface{}) func()
AddHandlerOnce allows you to add an event handler that will be fired the next time the event that matches the function fires. See AddHandler for more details.
func (*Session) Chat ¶ added in v0.0.2
func (s *Session) Chat(act enum.Action, dest enum.Destination, destID uint32, message string) (err error)
Chat sends a chat message (who'dve thought it?)
func (*Session) GamescriptCommand ¶ added in v0.0.2
GamescriptCommand sends a non-blocking Gamescript command to the server. You are expected to watch for events of type Gamescript to determine the result if you use this.
func (*Session) HeartbeatLatency ¶ added in v0.0.2
HeartbeatLatency returns the latency between heartbeat acknowledgement and heartbeat send.
func (*Session) Poll ¶ added in v0.0.2
func (s *Session) Poll(t enum.UpdateType, id uint32) (err error)
Poll sends a request to receive one update for the given UpdateType and ID. If you can't poll for the given UpdateType, this returns an error.
func (*Session) Rcon ¶ added in v0.0.2
Rcon sends a non-blocking RCON command to the server. Use this when you don't care what the result is - if you do, use RconSync(command).
func (*Session) RconSync ¶ added in v0.2.0
RconSync sends a blocking RCON command to the server, waits for a response, then returns a set of response packets. Please note: This will block your thread until we get a complete response from the server! If you don't care about the result, use Rcon(command).
func (*Session) RequestUpdates ¶ added in v0.0.2
func (s *Session) RequestUpdates(t enum.UpdateType, f enum.UpdateFrequency) (err error)
RequestUpdates sends a request to receive updates of the given type from the server at a given interval. Supplying a frequency of POLL is invalid and will return an error - use Session.Poll()
type State ¶ added in v0.0.2
type State struct { sync.RWMutex // Dedicated is set if the server reports itself to be a Dedicated Server (instead of a Listen Server). Dedicated bool `json:"dedicated"` // Name is the server's advertised Hostname. Name string `json:"name"` // Version is the server's currently running Version string. Version string `json:"version"` // ProtocolVersion is the server's protocol version (i.e what feature set it supports). ProtocolVersion uint8 `json:"protocol_version"` // NeedPass defines whether the server is private (i.e needs a password) NeedPass bool `json:"need-pass"` // Language is the given Server Language. // If you need the string version of a language, use // gopenttd.GetISOLanguage(OpenttdServerState.Language) or gopenttd.GetLanguage(OpenttdServerState.Language) Language util.OpenttdLanguage `json:"language"` // Landscape is the environment identifier. // If you need the string version of the environment, use // gopenttd.GetEnvironment(OpenttdServerState.Environment) Landscape util.OpenttdEnvironment `json:"landscape"` // Map is the name of the map currently running. Note that this will be set to "Random Map" if the map was generated by a seed. Map string `json:"map_name"` // Seed is the seed used to generate the map, if available (usually only through the admin port). nil if unavailable. Seed uint32 `json:"map_seed"` // MapHeight and MapWidth are the height and width of the current map in tiles. MapHeight uint16 `json:"map_height"` MapWidth uint16 `json:"map_width"` // DateStart and DateCurrent are time objects relating to the start of the game and the current date. DateStart time.Time `json:"date_start"` DateCurrent time.Time `json:"date_current"` // Clients is a map of client IDs and client data. Clients map[uint32]Client `json:"clients"` // Companies is a map of company IDs and company data. Companies map[uint8]Company `json:"companies"` }
A State contains the current known state of the server.
func (*State) Counts ¶ added in v0.0.2
Counts simply counts the number of companies, spectators, and clients connected. Note that Clients is a count of ALL clients, INCLUDING spectators. (i.e Clients will always be bigger than Spectators)
func (*State) OnInterface ¶ added in v0.0.2
OnInterface handles all events related to states.
type Welcome ¶ added in v0.0.2
type Welcome struct { Name string // Name of the Server (e.g. as advertised to master server). Version string // OpenTTD version string. Dedicated bool // Server is dedicated. Map string // Name of the Map. Seed uint32 // Random seed of the Map. Landscape uint8 // Landscape of the Map. StartDate uint32 // Start date of the Map. MapWidth uint16 // Map width. MapHeight uint16 // Map height. }
Welcome fires when receiving a Welcome packet, usually during join or after map load.