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 use Lionel's Legacy/TMCC command protocol. PyTrain Api is used by the PyTrain Alexa skill to enables 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.
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 frompypi
:
pip3 install pytrain-ogr-api
- Run the PyTrain Api server:
pytrain_api
This command launches a webserver that accepts requests on port 8000
and 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 directoryPyTrainApi
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 8000
and 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 unintensional 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 reasn, 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. Simply 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).
Cnanging other values will
break PyTrain Api. If you do mistakenly modify the file's contents or delete it, you can simply
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, lets look at the moving parts involved:
-
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.
-
Your local network. This can be completely wireless or a hybrid of wired and wireless devices.
-
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.
-
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.
-
An Alexa. This device is a wireless speaker and microphone. It supports skills, which are voice-activated apps that runs 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.
-
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.
-
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 runs on these computers, takes yur 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:
- Configure 2 Raspberry Pi 4 or 5 computers. Units with WiFi are preferred, as there are less wires.
- 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>
- 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.
- Go to your gateway and determine its external IP address. This address is assigned by your ISP (Comcast, Verizon, Spectrum, etc.). Write it down.
- Consult your gateway documentation 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).
- Say the following to your Alexa: Alexa, Open PyTrain
- 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 PyTrain 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 skill is listening. If the light goes out, simply say Alexa, Open PyTrain, 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 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 in order 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
Built Distribution
File details
Details for the file pytrain_ogr_api-1.1.4.tar.gz
.
File metadata
- Download URL: pytrain_ogr_api-1.1.4.tar.gz
- Upload date:
- Size: 48.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 47dd8bfdb012ec0b180bf9d6faf934ee8625e0a6b9306cf0dbbe3a6e3f201d4c |
|
MD5 | 140f08053a3b95a7389ae74c16ccbf93 |
|
BLAKE2b-256 | 0ac7a72be623a10a8ea0333f7699ebb504c026adc023ce47e4ce49fccb440761 |
Provenance
The following attestation bundles were made for pytrain_ogr_api-1.1.4.tar.gz
:
Publisher:
pypi-release.yml
on cdswindell/PyTrainApi
-
Statement:
- Statement type:
https://in-toto.io/Statement/v1
- Predicate type:
https://docs.pypi.org/attestations/publish/v1
- Subject name:
pytrain_ogr_api-1.1.4.tar.gz
- Subject digest:
47dd8bfdb012ec0b180bf9d6faf934ee8625e0a6b9306cf0dbbe3a6e3f201d4c
- Sigstore transparency entry: 207614776
- Sigstore integration time:
- Permalink:
cdswindell/PyTrainApi@590ddba48f9301732b10a4c2b38497d0790a4c3b
- Branch / Tag:
refs/tags/v1.1.4
- Owner: https://github.com/cdswindell
- Access:
public
- Token Issuer:
https://token.actions.githubusercontent.com
- Runner Environment:
github-hosted
- Publication workflow:
pypi-release.yml@590ddba48f9301732b10a4c2b38497d0790a4c3b
- Trigger Event:
push
- Statement type:
File details
Details for the file pytrain_ogr_api-1.1.4-py3-none-any.whl
.
File metadata
- Download URL: pytrain_ogr_api-1.1.4-py3-none-any.whl
- Upload date:
- Size: 42.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 3bd2dc8c669173cabbb3e54a3dcbfe3a41adbea60e604ee8e6c3e05dceccfa47 |
|
MD5 | 7c5978f900ceaf6cd31eb27d361d0929 |
|
BLAKE2b-256 | 7db93298626b0e89cde6e2c1f54be445f5f9130ca83522363ecefad53a1fefdd |
Provenance
The following attestation bundles were made for pytrain_ogr_api-1.1.4-py3-none-any.whl
:
Publisher:
pypi-release.yml
on cdswindell/PyTrainApi
-
Statement:
- Statement type:
https://in-toto.io/Statement/v1
- Predicate type:
https://docs.pypi.org/attestations/publish/v1
- Subject name:
pytrain_ogr_api-1.1.4-py3-none-any.whl
- Subject digest:
3bd2dc8c669173cabbb3e54a3dcbfe3a41adbea60e604ee8e6c3e05dceccfa47
- Sigstore transparency entry: 207614778
- Sigstore integration time:
- Permalink:
cdswindell/PyTrainApi@590ddba48f9301732b10a4c2b38497d0790a4c3b
- Branch / Tag:
refs/tags/v1.1.4
- Owner: https://github.com/cdswindell
- Access:
public
- Token Issuer:
https://token.actions.githubusercontent.com
- Runner Environment:
github-hosted
- Publication workflow:
pypi-release.yml@590ddba48f9301732b10a4c2b38497d0790a4c3b
- Trigger Event:
push
- Statement type: