Skip to main content

Restful API to control Lionel TMCC/Legacy engines, switches, and accesseries from a Raspberry Pi

Project description

PyTrain API

This project implements a RESTful API to PyTrain. Via the API, you can control and operate trains, switches, accessories, and any other equipment that uses Lionel's Legacy/TMCC command protocol. PyTrain Api is used by the PyTrain Alexa skill to enable voice-control of your layout.

PyTrain Api is developed in pure Python. It uses the FastAPI framework and includes an ASGI-compliant web server, Uvicorn. Once installed, it only takes one command to launch the PyTrain Api and begin serving requests.

PyTrain Api runs as a PyTrain client connected to another PyTrain server, or can act as both a PyTrain server and a PyTrain Api server. And, like PyTrain, PyTrain Api can run on a Raspberry Pi running 64-bit Bookworm distribution or later.

The PyTrain Api endpoints can be viewed here: https://cdswindell.github.io/PyTrainApi/pytrain-api-docs/

Table of Contents

Quick Start

Requirements

Minimum requirements to use PyTrain API are:

  • A Lionel Base 3 running the most current Lionel firmware and configured in infrastructure mode
  • A network-capable Raspberry Pi 4 or 5 running Raspberry PI OS 64-bit Bookworm
  • A Mac or Windows computer to set up the Raspberry Pi(s)
  • All hardware connected to the same Wi-Fi network
  • Python 3.10–3.12 installed (Python 3.11 is standard with the Bookworm release of Raspberry Pi OS)
  • Internet access (to download software)

Recommended:

  • A PyTrain server running on a separate Raspberry Pi 4 or 5 Wi-Fi-equipped computer with at least 2 GB of RAM running Raspberry PI OS 64-bit Bookworm

Notes:

  • It is recommended to have a Lionel LCS Ser2 module connected to your PyTrain server, as the Lionel Base 3 does not broadcast all layout activity
  • PyTrain is a command-line tool. It must be run from a Terminal window (macOS/Linux/Pi) or a Cmd shell (Windows). PyTrain does not have a GUI nor run as a native app.
  • PyTrain may work with an LCS Wi-Fi module, but this configuration hasn't been tested
  • The PyTrain CLI can be run on a Mac or Windows system. It allows complete control of all TMCC or Legacy-equipped devices as well as allows you to monitor all TMCC and Legacy commands

Installation

PyTrain Api can be run directly from a Python virtual environment or from a PyTrain Api development environment, The former is preferable if you do not plan on changing the PyTrain Api code itself. Both methods require the creation of a Python virtual environment.

Create a Python Virtual Environment

  • Open a Terminal shell window and navigate to the folder/directory where you will install PyTrain Api
  • Create a virtual environment with the command:
python3 -m venv PyTrainApiEnv
  • In the same terminal window, cd into the directory you created above and activate the environment:
cd PyTrainApiEnv
source bin/activate

Run PyTrain Api Directly

  • Use pip to install the PyTrain Api package from pypi:
pip3 install pytrain-ogr-api
  • Run the PyTrain Api server:
pytrain_api

This command launches a webserver that accepts requests on port 8000and connects to a PyTrain server. To see the list of available Api endpoints, open a web browser and go to http://<your local IP>:8000/pytrain.

Run PyTrain Api from a Development Environment

  • In the same terminal window where you created the virtual environment, cd into the directory you created above and download the PyTrain Api source code (this assumes you have installed the GitHub CLI):
gh repo clone cdswindell/PyTrainApi
  • cd into the directory PyTrainApi and activate the environment:
cd PyTrainApi
source ../bin/activate
  • Install the PyTrain Api required packages:
pip3 install -r requirements.txt
  • Run the PyTrain Api server:
cli/pytrain_api

This command launches a webserver that accepts requests on port 8000and connects to a PyTrain server. To see the list of available Api endpoints, open a web browser and go to http://<your local IP>:8000/pytrain.

Configuration

The PyTrain Api endpoints are all protected against unintentional as well as unwanted access. It does so by requiring an api token to be present in the header of each request. Modern programming languages make this easy to do.

Api tokens should be kept secure, just like the key to your house, otherwise, anyone could learn and use it. For this reason, ypu must generate the required keys yourself and keep them in a special file, the .env file. This file must be placed in the same directory you run the PyTrain Api program from.

PyTrain Api provides a special command to generate a correctly-configured .env file and populate it with an api token for your own use. To do so, cd to the directory where you plan to run the Api and type:

  • Run PyTrain Api Directly
pytrin_api -env
  • Run PyTrain Api from a Development Environment
cli/pytrin_api -env

Use the value assigned to the tag API_TOKEN as your secure PyTrain Api token. Include it in your request header with the tag X-API-Key, and you will be good to go. Below is an example of how to do this from Python:

headers = {"X-API-Key": "<Replace with the API_TOKEN from .env file>"}
response = requests.post(url, headers=headers)

You should not modify any values in .env unless you are using the Alexa Skill (see below). Changing other values will break PyTrain Api. If you do mistakenly modify the file's contents or delete it, you can regenerate it using the appropriate command above.

Alexa Skill

PyTrain Api is required to use the Alexa PyTrain skill. You may install PyTrain Api using either method described above.

Configuration

Before getting into the configuration details, let's look at the moving parts involved:

  1. Your Lionel Base 3. This device is connected to your local network and receives commands from a Cab 2, Cab 3, and/or PyTrain server. These commands are relayed onto your layout to control your equipment.

  2. Your local network. This can be completely wireless or a hybrid of wired and wireless devices.

  3. Your PyTrain API server. This is a computer on your local network where you have installed PyTrain API. It takes requests from the web in a specific format (HTTP or HTTPS) and relays them to your PyTrain server. PyTrain API can run on one of your existing computers (Mac or Windows), or, and a small, inexpensive Raspberry Pi.

  4. Your PyTrain server. This is another computer on your local network where you have installed PyTrain. PyTrain receives requests from PyTrain API and relays them to your Lionel Base 3 in the format it requires. It can also take input from a command line (CLI) or be embedded into one or more control panels to operate your layout via physical buttons, lights, dials, and knobs. It should run its own Raspberry Pi.

  5. An Alexa. This device is a wireless speaker and microphone. It supports skills, which are voice-activated apps that run on Alexa-enabled devices. You can use Alexa skills to perform tasks like telling jokes, getting weather updates, or controlling your Lionel layout. It connects to your local network.

  6. Your Gateway. This device connects your local network to the internet. It may have been provided by your Internet Service Provider (ISP), or you may have purchased it yourself. It is the bridge that lets devices on your local network talk to the internet and lets the internet talk to devices on your local network, like your Lionel Base 3.

  7. Amazon AWS. Amazon runs several large computing facilities around the world. Alexa skills send the voice input from your local alexa's to these computers to interpret, then execute software to fulfill your requests. The PyTrain Alexa skill, which is named My Layout, runs on these computers, takes your voice input and then calls back to the PyTrain API on your local network to control your layout.

Phew! Although there are a lot of moving parts, getting everything up and running is straightforward, thanks to the PyTrain software.

Here is what you need to do:

  1. Configure two Raspberry Pi 4 or 5 computers. Units with Wi-Fi are preferred, as there are fewer wires.
  2. Install PyTrain on one of them and start it with the command:
pytrain -base <ip address of your Lionel Base 3>

If you have a Lionel Lcs Ser2, connect it to this computer and start PyTrain with this command:

pytrain -ser -base <ip address of your Lionel Base 3>
  1. Install PyTrain Api on the other Raspberry Pi (using one of the two methods above) and start it with the appropriate command:
pytrain_api 

or

cli/pytrain_api

PyTrain Api will automatically find and connect to your PyTrain server.

  1. Go to your gateway and determine its external IP address. This address is assigned by your ISP (Comcast, Verizon, Spectrum, etc.). Write it down.
  2. Consult your gateway documentation on how to forward port 80 to port 8000 on your PyTrain API server. This will send all traffic from the outside world to port 8000 on your PyTrain Api server. You will need to repeat this step any time your external IP address changes (see Notes below).
  3. Say the following to your Alexa: Alexa, Open My Layout
  4. The PyTrain skill will ask you for the external IP address of your network. Give it the number you wrote down above.

Your PyTrain skill is now active and connected to your layout. To test it out, assuming you have an engine on the tracks with TMCC ID 67, try the following:

  • Ask My Layout to start up engine 67
  • Blow the horn on engine 67
  • toggle the bell on engine 67
  • accelerate engine 67 to speed step 10
  • stop engine 67
  • shut down engine 67 with dialog

As long as you see the blue light on your Alexa, the PyTrain My Layout skill is listening. If the light goes out, say: Alexa, Open My Layout, and speak your request.

Notes:

  • If your gateway supports Dynamic DNS, you can assign a domain name to your external network, and your gateway will automatically update it with your external IP address, should your ISP change it. Netgear, No-ip.com, and Dyn.com all provide dynamic dns services at a reasonable cost.

Additional Security

For additional security, you can configure an HTTPS server to proxy requests from the Alexa skill to the system running PyTrain API. This requires:

  • Install an additional web server that supports HTTPS secure communication. The nginx web server is an excellent candidate.
  • Configure ngnix to proxy HTTPS requests from port 443 to port 8000, where they are processed by PyTrain API.
  • Install an SSL certificate on your dynamic dns service
  • Configure the certificate and private key on your local proxy server.

These steps are not required but are suggested if you leave your layout unattended and powered on to prevent unwanted access.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pytrain_ogr_api-1.6.9.tar.gz (66.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pytrain_ogr_api-1.6.9-py3-none-any.whl (49.3 kB view details)

Uploaded Python 3

File details

Details for the file pytrain_ogr_api-1.6.9.tar.gz.

File metadata

  • Download URL: pytrain_ogr_api-1.6.9.tar.gz
  • Upload date:
  • Size: 66.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for pytrain_ogr_api-1.6.9.tar.gz
Algorithm Hash digest
SHA256 f80c43d04c676db9fcf3d3ef8ab863ed32b0c189397e707a0d88286cdee0aba1
MD5 9a84d957e7a630ea56d6b9bf94fff10b
BLAKE2b-256 db44ea4663cae22b359a8d7b9cb9da72b4fec13ec9ab9da3b30edfd810becd9a

See more details on using hashes here.

Provenance

The following attestation bundles were made for pytrain_ogr_api-1.6.9.tar.gz:

Publisher: pypi-release.yml on cdswindell/PyTrainApi

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file pytrain_ogr_api-1.6.9-py3-none-any.whl.

File metadata

File hashes

Hashes for pytrain_ogr_api-1.6.9-py3-none-any.whl
Algorithm Hash digest
SHA256 dd8c548eef451093bbb870889dca1498825ea8af76f072a3c4c98ef9efcada5b
MD5 8e08fa0f843eb4fa0de455ed5f3eb2e8
BLAKE2b-256 8cffac0d3d08bbbbd08fe5c9c6bed0a73d858bfc21781f237dd1e369117b8211

See more details on using hashes here.

Provenance

The following attestation bundles were made for pytrain_ogr_api-1.6.9-py3-none-any.whl:

Publisher: pypi-release.yml on cdswindell/PyTrainApi

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page