Hobby project (2018): Common Lisp minimal demonstration code for controlling Roco Z21 model railway command stations over LAN.
The Z21 command station communicates via UDP on port 21105 using a binary protocol. This library implements a subset of the protocol, providing high-level functions to control locomotives, turnouts, and track power interactively from the REPL.
- System info -- serial number, X-Bus version, firmware version
- Track power -- on, off, emergency stop
- Turnouts -- get state, set state, toggle
- Locomotives -- drive (speed, direction), toggle functions (light, sound, etc.)
- Locomode -- query DCC or Motorola format
- CV programming -- read CVs in service mode (direct mode)
- Broadcast -- get/set broadcast flags, listen for unsolicited messages
(ql:quickload "usocket")
(asdf:load-system "z21")Make sure the cl-z21 directory is in a location ASDF can find (e.g., ~/common-lisp/ or a directory registered in your ASDF source registry).
Edit globals.lisp to match your Z21 setup:
(defparameter *IP_ADDRESS* "192.168.0.111") ; Z21 IP address
(defparameter *PORT* 21105) ; Z21 UDP port (default);; System info
(z21-get-serial-number :verbose t)
(z21-get-firmware-version :verbose t)
;; Track power
(z21-set-track-power-on :verbose t)
(z21-set-stop :verbose t) ; emergency stop
;; Turnouts
(z21-get-turnout-info 0 :verbose t)
(z21-set-turnout 0 #b10 :verbose t) ; straight
(z21-set-turnout 0 #b01 :verbose t) ; diverging
(z21-switch-turnout 0 :verbose t) ; toggle
;; Locomotives
(z21-get-loco-info 3 :verbose t)
(z21-set-loco-drive 3 64 :direction 1 :verbose t) ; forward, speed 64/127
(z21-set-loco-function 3 0 #x01 :verbose t) ; light onSee examples.lisp for more usage patterns including CV reading and broadcast listening.
The library uses a coder/decoder registry pattern:
- Each Z21 command is registered as a
coderstruct that knows how to build the binary message - Each Z21 response is registered as a
decoderstruct that matches by byte prefix and knows how to parse the data z21-interactties them together: encode, send via UDP, receive, decode
| File | Purpose |
|---|---|
globals.lisp |
Z21 IP address and port |
octet-functions.lisp |
Byte manipulation utilities |
z21-interaction.lisp |
UDP socket send/receive layer |
message-coders.lisp |
Encode Z21 LAN protocol commands |
message-decoders.lisp |
Decode Z21 LAN protocol responses |
z21-functions.lisp |
High-level API |
examples.lisp |
Interactive usage examples (not loaded) |
This library implements a subset of the Z21 LAN protocol as documented in the official Roco specification.