README
¶
NTRIP Library
A comprehensive implementation of the NTRIP (Networked Transport of RTCM via Internet Protocol) protocol, with a focus on NTRIP Caster functionality.
Table of Contents
- Project Overview
- Project Structure
- Core Features
- Quick Start
- API Documentation
- Usage Examples
- Best Practices
- Troubleshooting
- Contributing
- License
Project Overview
This library provides a complete implementation of the NTRIP protocol, which is widely used in GNSS (Global Navigation Satellite System) applications for real-time data transfer. The core functionality is centered around the NTRIP Caster, which acts as a central hub for distributing RTCM (Radio Technical Commission for Maritime Services) correction data between reference stations and rovers.
Key Components
- NTRIP Caster: Core server implementation for handling NTRIP connections and data transfer
- NMEA Parser: Processing GPS data in NMEA format
- Utilities: Helper functions for NTRIP protocol processing
- Logging: Standard logging interface for the library
Project Structure
ntrip/
├── internal/ # Internal implementation details
├── log/ # Logging functionality
├── nmea/ # NMEA protocol processing
├── ntripcaster/ # NTRIP Caster implementation (core)
├── skill/ # AI skill for automated programming
├── utils/ # NTRIP protocol utilities
├── go.mod # Go module definition
├── go.sum # Go module dependencies
└── README.md # This documentation
Module Details
- log/: Provides logging interfaces and a null logger implementation
- nmea/: Handles NMEA message parsing, creation, and manipulation
- ntripcaster/: Core NTRIP Caster implementation with event-driven architecture
- utils/: Utility functions for processing NTRIP request headers
- internal/: Internal helper functions not exposed publicly
- skill/: AI skill for automated programming with the library
Core Features
NTRIP Caster
- Connection Management: Handles multiple concurrent NTRIP connections
- Event-Driven Architecture: Uses callbacks for connection and data events
- Mountpoint Support: Manages different mountpoints for data streams
- Client Tracking: Monitors online and alive clients
- Graceful Shutdown: Properly cleans up resources on shutdown
NMEA Processing
- Message Parsing: Parses NMEA format GPS data
- Message Creation: Creates valid NMEA messages
- Coordinate Manipulation: Gets and sets latitude/longitude coordinates
- Coordinate Offset: Supports offsetting coordinates by specified meters
- Validation: Checks if NMEA messages are valid
Utilities
- Request Processing: Parses and encodes NTRIP request headers
- Authentication: Supports basic authentication for NTRIP requests
Quick Start
Prerequisites
- Go 1.25.7 or later
- Git
Installation
go get gitee.com/unignss/ntrip
Basic Usage
Creating a Simple NTRIP Caster
import (
"gitee.com/unignss/ntrip/ntripcaster"
"gitee.com/unignss/ntrip/log"
)
func main() {
// Create default server options
opts := ntripcaster.DefaultServerOptions()
opts.Addr = ":2101" // Set port to 2101
// Create NTRIP Caster with options
caster := ntripcaster.NewNtripCaster(opts)
// Set null logger (or use your custom logger)
caster.SetLogger(log.NullLogger)
// Start the server
err := caster.Start()
if err != nil {
panic(err)
}
// Server is running
println("NTRIP Caster started on", caster.ListenAddr())
// Wait for shutdown (you can implement signal handling here)
caster.WaitShutdown()
}
API Documentation
NTRIP Caster
NtripCaster
- **NewNtripCaster(options ServerOptions) NtripCaster: Creates a new NTRIP Caster instance
- Start() error: Starts the NTRIP Caster server
- Close(): Closes the NTRIP Caster server
- ListenAddr() string: Returns the address the server is listening on
- GetOnline() int: Returns the number of online clients
- GetClientAliveN() int: Returns the number of alive clients
- StatusString() string: Returns the server status as a string
- SetLogger(logger Logger): Sets the logger for the server
- Actived() bool: Returns whether the server is active
- WaitShutdown(): Waits for the server to shutdown
Event Handlers
- OnNtripAccept(c *Client, req *utils.NtripRequestHead, data []byte): Called when a new NTRIP connection is accepted
- OnNtripDataRecv(c *Client, data []byte): Called when NTRIP data is received from a client
- OnNtripDataSend(c *Client, data []byte): Called when NTRIP data is sent to a client
- OnNtripClose(c *Client): Called when an NTRIP connection is closed
ServerOptions
- *DefaultServerOptions() ServerOptions: Creates default server options
- Addr string: Server address to listen on (e.g., ":2101")
- ReadTimeout time.Duration: Read timeout for client connections
- WriteTimeout time.Duration: Write timeout for client connections
NMEA
NMEA
- *NewNMEA() NMEA: Creates a new NMEA instance
- CheckNMEAIsOK() bool: Checks if NMEA message is valid
- GetLat() float64: Gets latitude in degrees
- GetLng() float64: Gets longitude in degrees
- SetLat(lat float64): Sets latitude in degrees
- SetLng(lng float64): Sets longitude in degrees
- Encode() string: Encodes NMEA data to string
- ParseText(text string) bool: Parses NMEA string to NMEA structure
- OffsetLat(metre float64): Offsets latitude by specified meters
- OffsetLng(metre float64): Offsets longitude by specified meters
- OffsetLatLng(lat_offset float64, lng_offset float64): Offsets both latitude and longitude by specified meters
Utilities
NtripRequestHead
- *NewNtripRequestHead() NtripRequestHead: Creates a new NTRIP request head instance
- ParseText(text string) bool: Parses NTRIP request text to structure
- Encode() string: Encodes NTRIP request to string
- SetUserPass(user string, pass string): Sets username and password for authentication
Logging
Logger
- Debug(v ...interface{}): Logs debug message
- Info(v ...interface{}): Logs info message
- Warn(v ...interface{}): Logs warning message
- Error(v ...interface{}): Logs error message
- Infof(format string, v ...interface{}): Logs formatted info message
NullLogger
A null logger implementation that discards all log messages, useful as a default logger when detailed logging is not needed.
Usage Examples
NTRIP Caster with Event Handlers
import (
"fmt"
"gitee.com/unignss/ntrip/ntripcaster"
"gitee.com/unignss/ntrip/utils"
"gitee.com/unignss/ntrip/log"
)
func main() {
// Create server options
opts := ntripcaster.DefaultServerOptions()
opts.Addr = ":2101"
// Create NTRIP Caster
caster := ntripcaster.NewNtripCaster(opts)
caster.SetLogger(log.NullLogger)
// Set up event handlers
caster.OnNtripAccept = func(c *ntripcaster.Client, req *utils.NtripRequestHead, data []byte) {
fmt.Printf("Client connected: %s, Mountpoint: %s\n", c.RemoteAddr(), req.Mp)
// Send ICY 200 OK response for NTRIP clients
c.PostBuf([]byte("ICY 200 OK\r\n\r\n"))
}
caster.OnNtripDataRecv = func(c *ntripcaster.Client, data []byte) {
fmt.Printf("Received data from client: %d bytes\n", len(data))
// Process received data (e.g., RTCM messages)
}
caster.OnNtripClose = func(c *ntripcaster.Client) {
fmt.Printf("Client disconnected: %s\n", c.RemoteAddr())
// Clean up resources if needed
}
// Start server
err := caster.Start()
if err != nil {
panic(err)
}
fmt.Println("NTRIP Caster started with event handlers")
caster.WaitShutdown()
}
Processing NMEA Messages
import (
"fmt"
"gitee.com/unignss/ntrip/nmea"
)
func main() {
// Create a new NMEA instance
nmeaMsg := nmea.NewNMEA()
// Set coordinates
nmeaMsg.SetLat(30.5)
nmeaMsg.SetLng(114.3)
// Get coordinates
lat := nmeaMsg.GetLat()
lng := nmeaMsg.GetLng()
fmt.Printf("Initial coordinates: Lat=%f, Lng=%f\n", lat, lng)
// Offset coordinates (meters)
nmeaMsg.OffsetLatLng(100, 200) // Move 100m north, 200m east
// Get updated coordinates
newLat := nmeaMsg.GetLat()
newLng := nmeaMsg.GetLng()
fmt.Printf("Updated coordinates: Lat=%f, Lng=%f\n", newLat, newLng)
// Encode NMEA message
encoded := nmeaMsg.Encode()
fmt.Printf("Encoded NMEA: %s\n", encoded)
// Check if NMEA is valid
isValid := nmeaMsg.CheckNMEAIsOK()
fmt.Printf("NMEA valid: %t\n", isValid)
}
NTRIP Request Processing
import (
"fmt"
"gitee.com/unignss/ntrip/utils"
)
func main() {
// Create a new NTRIP request head
req := utils.NewNtripRequestHead()
// Set up a GET request for a mountpoint
req.Method = "GET"
req.Mp = "MOUNT1"
// Add some headers
req.Head = make(map[string]string)
req.Head["User-Agent"] = "NTRIP Client"
// Encode request to string
encoded := req.Encode()
fmt.Printf("Encoded request:\n%s\n", encoded)
// Parse a request string
testReq := "GET /MOUNT1 HTTP/1.0\r\nUser-Agent: NTRIP Client\r\n\r\n"
parsedReq := utils.NewNtripRequestHead()
success := parsedReq.ParseText(testReq)
if success {
fmt.Printf("Parsed request: Method=%s, Mountpoint=%s\n", parsedReq.Method, parsedReq.Mp)
}
}
Best Practices
- Logging: Always use
log.NullLoggeras the default logger if you don't need detailed logging - Error Handling: Implement proper error handling for all NTRIP Caster operations
- Timeouts: Set appropriate timeouts for client connections to prevent resource leaks
- Event Handlers: Use event handlers to properly process NTRIP data and manage client connections
- Validation: Always validate NMEA messages before processing them
- Graceful Shutdown: Implement graceful shutdown for the NTRIP Caster to properly clean up resources
- Monitoring: Monitor the number of online clients to detect potential issues
- Authentication: Use proper authentication for sensitive NTRIP services
Troubleshooting
Common Issues
NTRIP Caster fails to start
- Possible causes: Port already in use, invalid address format, permission denied
- Solutions: Use a different port, check address format, run with appropriate permissions
Clients cannot connect
- Possible causes: Firewall blocking port, incorrect server address, network issues
- Solutions: Configure firewall, verify server address, check network connectivity
Data not being transmitted correctly
- Possible causes: Invalid NTRIP messages, network timeouts, incorrect event handlers
- Solutions: Validate NTRIP messages, adjust timeouts, check event handler implementation
Contributing
Development Setup
- Fork the repository
- Clone your fork
- Create a feature branch
- Make your changes
- Run tests
- Submit a pull request
Code Style
- Follow Go's standard code style
- Use
go fmtto format your code - Write clear, concise comments
- Test your changes
Testing
go test ./...
License
This project is licensed under the MIT License. See the LICENSE file for details.
Acknowledgments
- This project implements the NTRIP protocol as defined by the RTCM (Radio Technical Commission for Maritime Services)
- Thanks to all contributors who have helped improve this library
Contact
For questions or issues, please open an issue on the GitHub repository.
Version 1.0.0