tetra_pei

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2026 License: Apache-2.0 Imports: 10 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Tetra PEI

[!CAUTION] This is very much a work in progress and being tested at the moment. Contributions are welcome.

A small cross-platform Go library (with an optional CLI) for talking to a TETRA radio's PEI using AT commands. Two transports are supported:

  • USB bulk — Motorola radios (tested: MTP3xxx 0x0CAD:0x9013) expose the PEI as a vendor-specific USB device with raw bulk endpoints (no CDC-ACM), so there is no serial/tty node on macOS or Windows. This transport uses gousb (libusb bindings) and works on Linux, macOS, and Windows.
  • Serial — radios that expose the PEI as CDC-ACM or a real UART are driven via go.bug.st/serial. Point it at /dev/ttyUSB0, /dev/tty.usbserial-XYZ, COM3, etc.

Bring-your-own transport is also possible: implement the Transport interface and hand the result to Attach.

Prerequisites

  • Go 1.25+
  • For the USB transport only: libusb 1.0 and a C toolchain (gousb uses cgo):
    • macOS: brew install libusb pkg-config
    • Debian/Ubuntu: sudo apt install libusb-1.0-0-dev pkg-config
    • Windows: MinGW-w64 + libusb (or use zadig to bind WinUSB to the interface)
  • The radio's codeplug must have the PEI + AT/SDS options enabled. On Motorola MTP3xxx, if it enumerates as PID 0x9013, that part is done.
Linux permissions (USB transport)

On Linux, unprivileged processes can't grab a raw USB device by default, so you'll see libusb: bad access or select config: ... errors from ./tetra-pei. Install a udev rule instead of running as root:

sudo tee /etc/udev/rules.d/70-tetra-pei.rules >/dev/null <<'EOF'
# Motorola TETRA PEI (MTP3xxx / MTP85xx)
SUBSYSTEM=="usb", ATTRS{idVendor}=="0cad", ATTRS{idProduct}=="901[0-9a-f]", \
    MODE="0660", GROUP="plugdev", TAG+="uaccess"
EOF
sudo udevadm control --reload-rules && sudo udevadm trigger
# then unplug + replug the radio

If your login isn't in plugdev, either add it (sudo usermod -aG plugdev $USER + re-login) or replace the group line with MODE="0666" for a wider-open rule.

Build

cd tetra
go mod tidy
go build ./cmd/tetra-pei

Run the CLI

./tetra-pei --list                              # expect: 0x0cad:0x9013  <- PEI interface
./tetra-pei                                     # USB (default), interactive prompt
./tetra-pei --serial /dev/ttyUSB0 --baud 9600   # serial transport
./tetra-pei --trace                             # also log raw PEI bytes (tx/rx) to stderr

--list enumerates USB Motorola devices; serial ports are not auto-listed.

Prompt commands:

info                          probe operating mode / etc. (Motorola exposes little)
sds <issi> <text>             send a text SDS to an individual
sds @<gssi> <text>            send a text SDS to a talkgroup
status <issi> <name|hex>      send a pre-coded status SDS (e.g. "emergency", "0x8005")
status @<gssi> <name|hex>     send a pre-coded status SDS to a talkgroup
tg                            show current talkgroup
tg <gssi>                     select talkgroup
mode                          show operating mode (0=TMO, 1=DMO, 6=Gateway)
mode <n>                      set operating mode
report on|off                 toggle delivery-report requests on outgoing text SDS
autoreport on|off             toggle auto-emitting SDS-REPORT on inbound text (default on)
hmd <issi> <text>             set target radio's Home Mode Display text (PID 220 / 0xDC)
hmd <issi> <pid> <text>       ...with a non-default protocol identifier
raw AT+CTOM?                  send an arbitrary AT command
quit

Incoming SDS print automatically, e.g.:

[incoming] text  13371 -> 2040188  "hello"

Line editing: arrow-up / arrow-down scroll through previous commands, tab completes the top-level command name, Ctrl-C on an empty line quits. Persistent history is stored at ~/.tetra-pei-history (or under $XDG_STATE_HOME/tetra-pei/history if that variable is set).

Library usage

package main

import (
	"fmt"
	"log"

	"github.com/techwolf12/tetra_pei"
)

func main() {
	// USB (Motorola bulk):
	r, err := tetra_pei.OpenUSB(tetra_pei.MotorolaVID, tetra_pei.MTP3xxxPID)
	// Or serial (any CDC-ACM / UART PEI):
	//   r, err := tetra_pei.OpenSerial("/dev/ttyUSB0", tetra_pei.SerialOptions{Baud: 9600})
	if err != nil {
		log.Fatal(err)
	}
	defer r.Close()

	r.EnableSDSRouting()

	// Consume incoming messages.
	go func() {
		for msg := range r.Incoming() {
			fmt.Println("incoming:", msg) // msg.From, msg.To, msg.Text, msg.Raw
		}
	}()

	if err := r.SendSDS(13371, "hello from Go"); err != nil {
		log.Println("send:", err)
	}

	// Arbitrary AT:
	lines, _ := r.SendRaw("AT+CTOM?")
	fmt.Println(tetra_pei.Summarize(lines))

	select {} // keep running to receive
}
Adding a new radio

OpenUSB accepts any VID/PID pair, so most radios "just work" if you know theirs. To make one enumerate as a PEI in --list, add it to the device registry (usually from an init()):

tetra_pei.RegisterDevice(tetra_pei.DeviceProfile{
    Name:     "Acme TR-4200 PEI",
    VID:      0x1234,
    PIDStart: 0x5678, // set PIDEnd too if it's a range
})

If after testing this works, feel free to create a issue or send a PR to add it to the list!

Releasing

Releases are cut by pushing a vX.Y.Z git tag. The .github/workflows/release.yml workflow runs on a native ubuntu-latest runner with multi-arch libusb installed, producing both linux/amd64 and linux/arm64 cgo binaries in one shot.

Artifacts per release (Linux only for now):

  • GitHub release with .tar.gz archives and checksums.txt
  • Debian package (tetra-pei_X.Y.Z_amd64.deb, _arm64.deb) — installs the CLI plus the udev rule under /usr/lib/udev/rules.d/

macOS (Homebrew tap) and AUR are follow-up work: macOS binaries need a macos-latest runner because cross-compiling libusb from Linux is fragile, and AUR needs an AUR_KEY secret registered against aur.archlinux.org.

Cutting a release
git tag v0.1.0
git push origin v0.1.0

The workflow runs on tag push. Local dry-runs:

goreleaser check                     # validate config only (no build)
goreleaser build --snapshot --clean  # host-arch build; arm64 needs the
                                     # aarch64-linux-gnu-gcc toolchain

Notes and limitations

  • Site/identity info is thin. Motorola's PEI implements the TETRA-specific commands (CTOM, CTSDS, CMGS, CTSP, CTSDSR) but not most generic ones (CGMI/CGMM/CNUM/CREG/CSQ often return +CME ERROR: 4 = not supported). Richer serving-cell data needs Motorola's proprietary, non-public commands.
  • Own ISSI: since AT+CNUM is unsupported, read it from the To field of any incoming SDS.
  • A trailing +CME ERROR: 35 after a send is a known Motorola quirk and can be ignored; +CMGS: is the real success signal (this is what SendSDS keys on).
  • SDS decoding handles SDS-TL text (protocol id 0x82/0x02) with both 8-bit ISO-8859-1 and GSM 03.38 7-bit packed septets (coding byte 0x01 / 0x00), and LIP short location reports (protocol id 0x0A, ETSI TS 100 392-18-1 §6.2) into IncomingSDS.Location (lat, lon, velocity, heading, position error, reason for sending). Timestamped text variants and long/basic LIP PDU forms are not decoded — inspect IncomingSDS.Raw.
  • Automatic delivery reports. When a text SDS arrives with the SDS-TL "delivery-report-request" bit set (types 1 and 3 = "message received" and "both"), the library synthesises and sends the corresponding SDS-REPORT back to the originator on your behalf. Skipped for group-addressed traffic. Toggle at runtime with Radio.AutoReportReceipt(false) or the CLI's autoreport off.
  • Home Mode Display. Radio.SendHomeModeDisplay(issi, pid, text) targets the recipient's idle-screen banner via a single-byte-PID SDS (Motorola default: HomeModeDisplayPID = 0xDC / 220). For unrelated vendor-specific PDUs use the underlying SendSDSWithPID.
  • USB endpoint discovery assumes the PEI data is on interface 0. If SendRaw("AT") returns nothing over USB, check whether it's on interface 1 and adjust usb.go. This does not affect the serial transport.
  • Serial defaults are 9600 8-N-1 with no flow control. If your radio uses 38400 or hardware handshaking, pass explicit SerialOptions.

Documentation

Overview

Package tetra_pei talks to a Motorola TETRA radio's PEI (Peripheral Equipment Interface) using AT commands. Two transports are supported out of the box:

  • USB bulk (Motorola MTPx000: vendor-specific class, no CDC-ACM) via gousb. Enumerate with List and open with OpenUSB.
  • Serial (any PEI exposed as CDC-ACM or a real UART) via go.bug.st/serial. Open with OpenSerial.

Callers with their own transport can implement the Transport interface and attach it with Attach.

File layout:

radio.go      - Radio struct, Attach, Close
transport.go  - byte-level framing (line splitting, dispatch) over Transport
usb.go        - USB transport + OpenUSB + List
serial.go     - serial transport + OpenSerial
devices.go    - VID/PID registry (KnownDevices / RegisterDevice)
commands.go   - AT command API (SendRaw, SendSDS, Ping, ...)
sds.go        - SDS PDU encode/decode and CTSDSR parsing
Example (LocationWebhook)

This example listens for incoming LIP short location reports (SDS protocol id 0x0A) and POSTs each decoded fix as JSON to a webhook. Combined with a rule engine on the server side, it turns every automatic-position-reporting radio into a data source for your ops dashboard, without touching the radio codeplug.

The example omits an "// Output:" comment because it requires a real radio; godoc still shows the source but `go test` won't execute it.

package main

import (
	"bytes"
	"context"
	"encoding/json"
	"log"
	"math"
	"net/http"
	"time"

	tetra_pei "github.com/techwolf12/tetra_pei"
)

func main() {
	// Swap OpenSerial for a CDC-ACM / UART PEI, or Attach for any Transport.
	r, err := tetra_pei.OpenUSB(tetra_pei.MotorolaVID, tetra_pei.MTP3xxxPID)
	if err != nil {
		log.Fatal(err)
	}
	defer r.Close()
	r.EnableSDSRouting()

	const webhookURL = "https://ops.example.internal/tetra/positions"
	client := &http.Client{Timeout: 5 * time.Second}

	// Optional fields use pointers so JSON emits `null` (via omitempty
	// they disappear entirely) when the radio didn't report them.
	type position struct {
		From                string    `json:"from"`
		Lat                 float64   `json:"lat"`
		Lon                 float64   `json:"lon"`
		HeadingDeg          *float64  `json:"heading_deg,omitempty"`
		VelocityKMH         *float64  `json:"velocity_kmh,omitempty"`
		PositionErrorMeters *float64  `json:"position_error_m,omitempty"`
		Reason              *uint8    `json:"reason,omitempty"`
		ReceivedAt          time.Time `json:"received_at"`
	}

	nilIfNaN := func(v float64) *float64 {
		if math.IsNaN(v) {
			return nil
		}
		return &v
	}

	for msg := range r.Incoming() {
		if msg.Kind != "location" {
			continue
		}
		loc := msg.Location
		if math.IsNaN(loc.Lat) || math.IsNaN(loc.Lon) {
			continue // undecodable variant (long/basic LIP PDU); inspect msg.Raw
		}

		p := position{
			From:                msg.From,
			Lat:                 loc.Lat,
			Lon:                 loc.Lon,
			HeadingDeg:          nilIfNaN(loc.HeadingDeg),
			VelocityKMH:         nilIfNaN(loc.VelocityKMH),
			PositionErrorMeters: nilIfNaN(loc.PositionErrorMeters),
			ReceivedAt:          time.Now().UTC(),
		}
		if loc.HasReason {
			p.Reason = &loc.Reason
		}

		body, err := json.Marshal(p)
		if err != nil {
			log.Printf("marshal position: %v", err)
			continue
		}

		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		req, err := http.NewRequestWithContext(ctx, http.MethodPost, webhookURL, bytes.NewReader(body))
		if err != nil {
			cancel()
			log.Printf("build request: %v", err)
			continue
		}
		req.Header.Set("Content-Type", "application/json")

		resp, err := client.Do(req)
		cancel()
		if err != nil {
			log.Printf("post %s: %v", webhookURL, err)
			continue
		}
		_ = resp.Body.Close()

		log.Printf("posted position from %s (%.6f, %.6f) status=%d",
			msg.From, loc.Lat, loc.Lon, resp.StatusCode)
	}
}
Example (SdsWebServer)

This example wraps a Radio in a tiny HTTP server: it displays incoming text SDS in a browser and lets you send outbound text SDS from a form. Handy as a lightweight dispatcher's console or an integration point for other services.

Endpoints:

GET  /            HTML page with the last N messages and a send form
GET  /messages    JSON array of the same messages (for AJAX polling)
POST /send        form-post: issi=<int>, text=<string>

The example omits an "// Output:" comment because it requires a real radio; godoc still shows the source but `go test` won't execute it.

package main

import (
	"context"
	"encoding/json"
	"errors"
	"html/template"
	"log"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"sync"
	"syscall"
	"time"

	tetra_pei "github.com/techwolf12/tetra_pei"
)

// This example wraps a Radio in a tiny HTTP server: it displays incoming
// text SDS in a browser and lets you send outbound text SDS from a form.
// Handy as a lightweight dispatcher's console or an integration point
// for other services.
//
// Endpoints:
//
//	GET  /            HTML page with the last N messages and a send form
//	GET  /messages    JSON array of the same messages (for AJAX polling)
//	POST /send        form-post: issi=<int>, text=<string>
//
// The example omits an "// Output:" comment because it requires a real
// radio; godoc still shows the source but `go test` won't execute it.
func main() {
	r, err := tetra_pei.OpenUSB(tetra_pei.MotorolaVID, tetra_pei.MTP3xxxPID)
	if err != nil {
		log.Fatal(err)
	}
	defer r.Close()
	r.EnableSDSRouting()

	// Ring buffer of the last 256 inbound text messages.
	type recorded struct {
		At    time.Time `json:"at"`
		From  string    `json:"from"`
		Text  string    `json:"text"`
		Group bool      `json:"group"`
	}
	const keep = 256
	var (
		mu       sync.Mutex
		received []recorded
	)
	push := func(m recorded) {
		mu.Lock()
		defer mu.Unlock()
		received = append(received, m)
		if len(received) > keep {
			received = received[len(received)-keep:]
		}
	}
	snapshot := func() []recorded {
		mu.Lock()
		defer mu.Unlock()
		out := make([]recorded, len(received))
		copy(out, received)
		return out
	}

	// Fan incoming text into the ring buffer. Delivery reports and
	// locations are ignored here; wire them up if you need them too.
	go func() {
		for msg := range r.Incoming() {
			if msg.Kind != "text" {
				continue
			}
			push(recorded{
				At:    time.Now().UTC(),
				From:  msg.From,
				Text:  msg.Text,
				Group: msg.Group,
			})
		}
	}()

	tmpl := template.Must(template.New("").Parse(sdsPageTemplate))

	mux := http.NewServeMux()

	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		if req.URL.Path != "/" {
			http.NotFound(w, req)
			return
		}
		if err := tmpl.Execute(w, snapshot()); err != nil {
			log.Printf("render: %v", err)
		}
	})

	mux.HandleFunc("/messages", func(w http.ResponseWriter, req *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(snapshot())
	})

	mux.HandleFunc("/send", func(w http.ResponseWriter, req *http.Request) {
		if req.Method != http.MethodPost {
			http.Error(w, "POST only", http.StatusMethodNotAllowed)
			return
		}
		if err := req.ParseForm(); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		issi, err := strconv.Atoi(req.FormValue("issi"))
		if err != nil {
			http.Error(w, "invalid issi", http.StatusBadRequest)
			return
		}
		text := req.FormValue("text")
		if text == "" {
			http.Error(w, "empty text", http.StatusBadRequest)
			return
		}
		if err := r.SendSDS(issi, text); err != nil {
			http.Error(w, err.Error(), http.StatusBadGateway)
			return
		}
		http.Redirect(w, req, "/", http.StatusSeeOther)
	})

	srv := &http.Server{
		Addr:              ":8080",
		Handler:           mux,
		ReadHeaderTimeout: 5 * time.Second,
	}

	// Graceful shutdown on Ctrl-C so the radio's Close still runs.
	stop := make(chan os.Signal, 1)
	signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		<-stop
		ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
		defer cancel()
		_ = srv.Shutdown(ctx)
	}()

	log.Printf("SDS console listening on %s", srv.Addr)
	if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
		log.Fatal(err)
	}
}

const sdsPageTemplate = `<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>tetra-pei SDS console</title>
    <style>
        body { font-family: system-ui, sans-serif; max-width: 60rem; margin: 2rem auto; padding: 0 1rem; }
        table { width: 100%; border-collapse: collapse; }
        th, td { text-align: left; padding: 0.25rem 0.5rem; border-bottom: 1px solid #eee; }
        input[type=text], input[type=number] { padding: 0.4rem; }
        form { margin: 1rem 0; display: flex; gap: 0.5rem; }
        form input[name=text] { flex: 1; }
    </style>
</head>
<body>
    <h1>SDS console</h1>
    <form method="post" action="/send">
        <input type="number" name="issi" placeholder="destination ISSI" required>
        <input type="text"   name="text" placeholder="message" maxlength="140" required>
        <button type="submit">Send</button>
    </form>
    <h2>Received ({{len .}})</h2>
    <table>
        <thead><tr><th>Time (UTC)</th><th>From</th><th>To</th><th>Text</th></tr></thead>
        <tbody>
        {{range .}}
            <tr>
                <td>{{.At.Format "15:04:05"}}</td>
                <td>{{.From}}</td>
                <td>{{if .Group}}group{{else}}me{{end}}</td>
                <td>{{.Text}}</td>
            </tr>
        {{else}}
            <tr><td colspan="4"><em>Nothing yet — waiting for inbound SDS.</em></td></tr>
        {{end}}
        </tbody>
    </table>
</body>
</html>`
Example (StatusTriggersHomeModeDisplay)

This example listens for incoming pre-coded status SDS messages, and each time it sees status value 3333 it pushes the next banner from a rotating list to the sender's Home Mode Display. Combined, this turns an SDS status button on the sender's radio into a "next slide" trigger for a shared banner rotation.

The example omits an "// Output:" comment because it requires a real radio; godoc still shows the source but `go test` won't execute it.

package main

import (
	"log"
	"strconv"

	tetra_pei "github.com/techwolf12/tetra_pei"
)

func main() {
	// Swap OpenSerial for a CDC-ACM / UART PEI, or Attach for any Transport.
	r, err := tetra_pei.OpenUSB(tetra_pei.MotorolaVID, tetra_pei.MTP3xxxPID)
	if err != nil {
		log.Fatal(err)
	}
	defer r.Close()

	// Ask the radio to deliver incoming status/text SDS to us.
	r.EnableSDSRouting()

	banners := []string{
		"Shift 1: OPS Team A",
		"Shift 2: OPS Team B",
		"All-hands 09:00",
		"Comms check @ 12:00",
	}
	const trigger tetra_pei.Status = 3333

	var next int
	for msg := range r.Incoming() {
		if msg.Kind != "status" || msg.StatusValue != trigger {
			continue
		}
		issi, err := strconv.Atoi(msg.From)
		if err != nil {
			log.Printf("skipping status from non-numeric sender %q", msg.From)
			continue
		}
		banner := banners[next%len(banners)]
		next++

		if err := r.SendHomeModeDisplay(issi, tetra_pei.HomeModeDisplayPID, banner); err != nil {
			log.Printf("HMD send to %d failed: %v", issi, err)
			continue
		}
		log.Printf("pushed banner %q to %d", banner, issi)
	}
}

Index

Examples

Constants

View Source
const (
	ModeTMO     = 0
	ModeDMO     = 1
	ModeGateway = 6
)

Operating-mode constants for CTOM. Values follow the Motorola PEI: 0=TMO (trunked), 1=DMO (direct), 6=Gateway. Other values are radio-specific.

View Source
const (
	NoParity    = serial.NoParity
	OddParity   = serial.OddParity
	EvenParity  = serial.EvenParity
	MarkParity  = serial.MarkParity
	SpaceParity = serial.SpaceParity

	OneStopBit           = serial.OneStopBit
	OnePointFiveStopBits = serial.OnePointFiveStopBits
	TwoStopBits          = serial.TwoStopBits
)
View Source
const (
	MotorolaVID = 0x0CAD // Motorola Solutions / CGISS
	MTP3xxxPID  = 0x9013 // MTP3xxx PEI interface
)
View Source
const HomeModeDisplayPID byte = 0xDC

HomeModeDisplayPID is the SDS-TL protocol identifier Motorola radios interpret as a "Home Mode Display" text update: the received text replaces the radio's idle-screen banner. Other vendors use different PIDs; the SendHomeModeDisplay helper lets callers override it.

Variables

This section is empty.

Functions

func Decode7BitGSM

func Decode7BitGSM(packed []byte, septetCount int) string

Decode7BitGSM unpacks GSM 03.38 default-alphabet septets from packed and returns the decoded string. septetCount is the number of septets to extract; the caller derives it from the SDS-TL bit length (usually (lengthBits - 32) / 7 for a text-messaging PDU with the standard 4-byte header). Unknown septets in the base table are skipped; unknown escape septets (0x1B + X) are skipped rather than emitting a replacement.

func EncodeGenericSDS

func EncodeGenericSDS(pid byte, payload []byte) []byte

EncodeGenericSDS builds a minimal SDS-TL PDU consisting of a single protocol-identifier byte followed by the raw payload. Use this for vendor-specific PIDs (e.g. HomeModeDisplayPID for Motorola HMD) where the receiving radio interprets the body according to its own rules.

func EncodeSDSReport

func EncodeSDSReport(ref byte, deliveryStatus uint8) []byte

EncodeSDSReport builds an SDS-REPORT PDU (SDS-TL message type 1) that acknowledges a received message. deliveryStatus is a 5-bit code — 0 means "message received" (successful delivery). The PDU is 25 bits of semantic content padded to 32 bits (4 bytes) so it fits AT+CMGS with a bit-length of 32.

func EncodeTextSDS

func EncodeTextSDS(ref byte, text string) []byte

EncodeTextSDS builds an SDS-TL text PDU (protocol id 0x82) carrying text as 8-bit ISO-8859-1. Layout: [0x82][0x02][ref][0x01] + text bytes.

func EncodeTextSDSWithReport

func EncodeTextSDSWithReport(ref byte, text string) []byte

EncodeTextSDSWithReport is EncodeTextSDS but sets the SDS-TRANSFER "delivery report request" bits to "message received" (0b01), so the receiving network element will emit an SDS-REPORT back to us.

func IsPEI

func IsPEI(pid uint16) bool

IsPEI reports whether a Motorola product id is a known TETRA PEI interface. Kept for backwards compatibility , new code should use LookupDevice, which handles arbitrary VIDs.

func List

func List() ([]uint16, error)

List returns the product IDs of attached Motorola (0x0CAD) USB devices. It only enumerates the Motorola VID today; if you need broader scanning, iterate KnownDevices and call gousb directly.

func RegisterDevice

func RegisterDevice(p DeviceProfile)

RegisterDevice appends a profile to the known-device registry. Safe from init(); safe for concurrent callers.

func Summarize

func Summarize(lines []string) string

Summarize renders SendRaw output for display, translating +CME errors.

Types

type DeliveryReport

type DeliveryReport struct {
	Ref            byte  // original message reference the report refers to
	Delivered      bool  // true when DeliveryStatus == 0
	DeliveryStatus uint8 // raw 5-bit delivery-status field (0 = received)
}

DeliveryReport is a decoded SDS-REPORT PDU (SDS-TL message type 1).

func DecodeDeliveryReport

func DecodeDeliveryReport(pdu []byte) (DeliveryReport, error)

DecodeDeliveryReport parses an SDS-REPORT PDU with the layout defined in ETSI TS 100 392-5 §29.4.3.10:

PID(8) msg-type(4) delivery-status(5) message-reference(8) [padding]

Returns an error if the PDU is not an SDS-REPORT.

type DeviceProfile

type DeviceProfile struct {
	Name     string // human-readable, e.g. "Motorola MTP3xxx PEI"
	VID      uint16
	PIDStart uint16 // inclusive
	PIDEnd   uint16 // inclusive; if 0, matches PIDStart only
}

DeviceProfile describes a USB VID/PID (or PID range) that the library treats as a TETRA PEI. Register your own via RegisterDevice; enumerate via LookupDevice / KnownDevices.

func KnownDevices

func KnownDevices() []DeviceProfile

KnownDevices returns a snapshot of the current registry.

func LookupDevice

func LookupDevice(vid, pid uint16) *DeviceProfile

LookupDevice returns the first matching profile for the given VID/PID, or nil if none is registered.

func (DeviceProfile) Matches

func (p DeviceProfile) Matches(vid, pid uint16) bool

Matches reports whether the profile applies to the given VID/PID.

type IncomingSDS

type IncomingSDS struct {
	AIService   int            // TETRA AI service (12 = SDS-TL, 13 = status)
	From        string         // calling party ISSI
	To          string         // called party ISSI (often your own ISSI)
	Group       bool           // true if the message was addressed to a talkgroup (GSSI)
	Kind        string         // "text", "status", "location", "delivery-report", or "unknown"
	Text        string         // decoded text (Kind == "text")
	StatusValue Status         // decoded pre-coded status (Kind == "status")
	Location    Location       // decoded location (Kind == "location"); zero if not a short LR
	Report      DeliveryReport // decoded delivery report (Kind == "delivery-report")
	Raw         string         // raw PDU hex

	// SDS-TRANSFER-only (Kind == "text"): the SDS-TL message reference and
	// whether the sender asked us to emit a delivery report back to them.
	// ReportRequestType is 0=none, 1=received, 2=consumed, 3=both.
	MessageRef        byte
	ReportRequestType uint8
}

IncomingSDS is a decoded inbound short data message.

func (IncomingSDS) String

func (m IncomingSDS) String() string

type Location

type Location struct {
	PDUType             uint8   // LIP PDU type (0 = short location report)
	TimeElapsed         uint8   // 2-bit "time elapsed since position fix" index
	Lat                 float64 // WGS-84 degrees; NaN if not decoded
	Lon                 float64 // WGS-84 degrees; NaN if not decoded
	PositionErrorMeters float64 // upper bound in metres; +Inf for > 200 km; NaN unknown
	VelocityKMH         float64 // decoded from 7-bit index; NaN if unknown
	VelocityRaw         uint8   // raw 7-bit velocity index (0..127)
	HeadingDeg          float64 // 0..337.5 in 22.5° steps; NaN if unknown
	HeadingRaw          uint8   // raw 4-bit heading index (0..15)
	Reason              uint8   // "reason for sending" (valid only when HasReason)
	HasReason           bool
}

Location is a decoded LIP short location report (ETSI TS 100 392-18-1 §6.2). Fields that were not present or not decodable are NaN (floats) or false (HasReason). Longer LIP PDU variants (long / basic / velocity / acknowledged) are left raw — inspect IncomingSDS.Raw.

func DecodeLIP

func DecodeLIP(pdu []byte) (Location, error)

DecodeLIP decodes a Location Information Protocol short location report PDU (SDS with protocol id 0x0A). The layout follows ETSI TS 100 392-18-1 §6.2: 4-bit PDU type, 2-bit time elapsed, 25-bit longitude, 24-bit latitude, 3-bit position error, 7-bit horizontal velocity, 4-bit direction of travel, 1-bit "additional data" flag, then an optional 8-bit reason for sending. Only PDUType == 0 is decoded; other PDU types return the raw PDUType field with everything else NaN.

type Parity

type Parity = serial.Parity

Parity and StopBits alias the go.bug.st/serial values so callers don't need to import the underlying package for basic configuration.

type Radio

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

Radio is an open connection to a TETRA radio's PEI over some Transport.

func Attach

func Attach(t Transport) *Radio

Attach wraps a Transport in a Radio and starts the framing goroutine. It's used by OpenUSB and OpenSerial, and is exported so callers can bring their own Transport (e.g. for tests or exotic hardware).

func OpenSerial

func OpenSerial(port string, opts SerialOptions) (*Radio, error)

OpenSerial opens a serial port and returns a Radio attached to it. Use this for PEIs exposed as CDC-ACM or a real UART. See OpenUSB for the USB-bulk path.

func OpenUSB

func OpenUSB(vid, pid uint16) (*Radio, error)

OpenUSB finds and opens the radio with the given vendor/product id and starts a framing goroutine. This is the USB-bulk entry point; use OpenSerial for radios exposed as CDC-ACM or a real UART.

func (*Radio) AutoReportReceipt

func (r *Radio) AutoReportReceipt(on bool)

AutoReportReceipt controls whether the library automatically sends an SDS-REPORT back to the sender when it receives a text SDS with the SDS-TL "delivery-report-request" bit set. Enabled by default.

func (*Radio) Close

func (r *Radio) Close() error

Close cancels the reader and releases the underlying Transport.

func (*Radio) CurrentTalkgroup

func (r *Radio) CurrentTalkgroup() (int, error)

CurrentTalkgroup queries the currently selected talkgroup via AT+CTGS? and returns the GSSI. The Motorola reply is typically "+CTGS: <n>,<gssi>"; we always take the last integer field.

func (*Radio) EnableSDSRouting

func (r *Radio) EnableSDSRouting()

EnableSDSRouting asks the radio to deliver incoming text/status SDS to us. PID values follow ETSI TS 100 392-5; adjust for the SDS types you want.

func (*Radio) Incoming

func (r *Radio) Incoming() <-chan IncomingSDS

Incoming returns a channel of decoded inbound SDS messages.

func (*Radio) OperatingMode

func (r *Radio) OperatingMode() (int, error)

OperatingMode queries the radio's current operating mode via AT+CTOM? and returns the numeric mode reported.

func (*Radio) Ping

func (r *Radio) Ping() bool

Ping returns true if the radio answers AT with OK.

func (*Radio) RequestDeliveryReports

func (r *Radio) RequestDeliveryReports(on bool)

RequestDeliveryReports controls whether subsequent SendSDS/SendSDSToGroup calls set the SDS-TL "delivery report requested" bit. When on, expect an incoming SDS with Kind == "delivery-report" from the recipient side.

func (*Radio) SelectTalkgroup

func (r *Radio) SelectTalkgroup(gssi int) error

SelectTalkgroup selects a talkgroup by GSSI via AT+CTGS=1,<gssi>. The first argument is the "talkgroup class" (1 = individual folder), per the Motorola PEI convention.

func (*Radio) SendDeliveryReport

func (r *Radio) SendDeliveryReport(issi int, ref byte, status uint8) error

SendDeliveryReport sends an SDS-REPORT PDU (ETSI TS 100 392-5 §29.4.3.10) to the given ISSI, acknowledging a previously received message. status is the 5-bit delivery status; 0 means "message received" (success). The PDU is transmitted on AI service 12 (SDS-TL individual).

func (*Radio) SendHomeModeDisplay

func (r *Radio) SendHomeModeDisplay(issi int, pid byte, text string) error

SendHomeModeDisplay sends a Home Mode Display update to the given ISSI: the recipient's radio replaces its idle-screen banner with the supplied text. pid is the protocol identifier (use HomeModeDisplayPID = 0xDC for Motorola; other vendors may differ). The text is transmitted as 8-bit ISO-8859-1 bytes.

func (*Radio) SendRaw

func (r *Radio) SendRaw(cmd string) ([]string, error)

SendRaw sends an AT command and collects the response lines up to a terminator (OK / ERROR / +CME ERROR) or a 3s timeout. Command exchanges are serialised — concurrent SendRaw / SendSDS / SendStatus / ... callers wait their turn, so responses cannot interleave.

func (*Radio) SendSDS

func (r *Radio) SendSDS(issi int, text string) error

SendSDS sends a text SDS to an individual ISSI (SDS-TL, AI service 12).

func (*Radio) SendSDSToGroup

func (r *Radio) SendSDSToGroup(gssi int, text string) error

SendSDSToGroup sends a text SDS to a talkgroup (GSSI). Same PDU as an individual message; the second AT+CTSDS argument switches the PEI to group-addressed mode.

func (*Radio) SendSDSWithPID

func (r *Radio) SendSDSWithPID(issi int, pid byte, payload []byte) error

SendSDSWithPID sends an SDS-TL PDU consisting of a single protocol identifier byte followed by the raw payload, addressed to an individual ISSI. Useful for vendor-specific PDUs such as Motorola's Home Mode Display (PID 0xDC).

func (*Radio) SendStatus

func (r *Radio) SendStatus(issi int, s Status) error

SendStatus sends a pre-coded status SDS (AI service 13) to an individual ISSI. Motorola's PEI accepts the status as a 4-char hex payload after AT+CMGS with a length of 16 bits.

func (*Radio) SendStatusToGroup

func (r *Radio) SendStatusToGroup(gssi int, s Status) error

SendStatusToGroup sends a pre-coded status SDS to a talkgroup (GSSI).

func (*Radio) SetOperatingMode

func (r *Radio) SetOperatingMode(mode int) error

SetOperatingMode issues AT+CTOM=<mode>.

func (*Radio) SetTrace

func (r *Radio) SetTrace(fn TraceFunc)

SetTrace installs (or clears with nil) a trace callback. Safe to call at any time; calls to fn are serialised via an internal RWMutex.

type SerialOptions

type SerialOptions struct {
	Baud     int      // default 9600
	DataBits int      // default 8
	Parity   Parity   // default NoParity
	StopBits StopBits // default OneStopBit
}

SerialOptions configures a serial-port transport. Zero values pick sensible defaults: 9600 8-N-1, no flow control.

type Status

type Status uint16

Status is a TETRA pre-coded status value carried by SDS AI service 13. ETSI TS 100 392-2 reserves the range 0x8000..0xFFFF for pre-coded values; 0x0000..0x7FFF is user-defined by the operator.

const StatusEmergency Status = 0x8000

StatusEmergency is the ETSI-reserved emergency status.

func ParseStatus

func ParseStatus(s string) (Status, error)

ParseStatus accepts a canonical name (e.g. "emergency"), a hex literal ("0x8005" or "8005"), or a decimal integer, and returns the matching Status. Names are case-insensitive.

func (Status) String

func (s Status) String() string

String returns the canonical name if known, otherwise "0xNNNN".

type StopBits

type StopBits = serial.StopBits

Parity and StopBits alias the go.bug.st/serial values so callers don't need to import the underlying package for basic configuration.

type TraceFunc

type TraceFunc func(dir string, data []byte)

TraceFunc is invoked (if set) on every chunk of PEI bytes moving in or out. dir is "tx" for host->radio and "rx" for radio->host. Implementations must not retain data past the call — the buffer is reused.

type Transport

type Transport interface {
	Read(p []byte) (int, error)
	Write(p []byte) (int, error)
	Close() error
}

Transport is a byte-oriented full-duplex link to a TETRA PEI.

Implementations must arrange for an in-flight Read to return an error once Close has been called, so the framing goroutine in readLoop can exit. Writes are serialised by Radio, so implementations need not be safe for concurrent Write calls, but Read and Write must be safe to call from different goroutines (as Radio does).

Directories

Path Synopsis
cmd
tetra-pei command
Command tetra-pei is a thin CLI over the tetra_pei library: query the radio, send SDS, and print incoming SDS as they arrive.
Command tetra-pei is a thin CLI over the tetra_pei library: query the radio, send SDS, and print incoming SDS as they arrive.

Jump to

Keyboard shortcuts

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