gpsgen

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2023 License: MIT Imports: 18 Imported by: 8

README

GPS data generator
GPSGen

GPS data generator based on predefined routes. Supports GPX and GeoJSON route formats.

This library can be used in testing and debugging applications or devices dependent on GPS/GLONASS/ETC, allowing you to simulate locations for checking their functionality without actual movement.


Coverage Status Docs Go Report Card Actions

Table of Contents

Installation

$ go get github.com/mmadfox/go-gpsgen

Example

package main

import (
	"fmt"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/google/uuid"
	"github.com/mmadfox/go-gpsgen"
)

const (
	numTracksPerRoute = 3
	numTrackers       = 1000
	flushInterval     = 3 * time.Second
)

func main() {
	lon := 37.625616307117696
	lat := 55.75350460378772

	genOpts := gpsgen.NewOptions()
	genOpts.Interval = flushInterval
	gen := gpsgen.New(genOpts)

	// For network transmission
	gen.OnPacket(func(b []byte) {
		// udp.send(b)
	})

	gen.OnError(func(err error) {
		fmt.Println("[ERROR]", err)
	})

	gen.OnNext(func() {
		fmt.Println("tracker state changed successfully")
	})

    // Generate random routes
	for i := 0; i < numTrackers; i++ {
		tracker := gpsgen.NewTracker()
		tracker.SetUserID(uuid.NewString())
		route := gpsgen.RandomRoute(lon, lat, numTracksPerRoute, gpsgen.RouteLevelM)
		tracker.AddRoute(route)
		gen.Attach(tracker)
	}

	terminate(func() {
		gen.Close()
	})

	gen.Run()
}

func terminate(fn func()) {
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan,
		syscall.SIGHUP,
		syscall.SIGINT,
		syscall.SIGTERM,
		syscall.SIGQUIT)
	go func() {
		<-sigChan
		fn()
	}()
}

Routes

GeoJSON
tracker := gpsgen.NewDroneTracker()

route, err := gpsgen.DecodeGeoJSONRoutes(geoJSONBytes)
if err != nil {
	panic(err)
}

tracker.AddRoute(route...)
// ...
GPX
tracker := gpsgen.NewDroneTracker()

route, err := gpsgen.DecodeGPXRoutes(GPXBytes)
if err != nil {
	panic(err)
}

tracker.AddRoute(route...)
// ...
Random
tracker := gpsgen.NewDroneTracker()

// lon, lat, numTracks, zoomLevel
lon := 28.31261399982
lat := 53.247483804819666
numTracks := 2

route := gpsgen.RandomRoute(lon, lat, numTracks, gpsgen.RouteLevelXL)

tracker.AddRoute(route...)
// ...

Sensors

A sensor provides a flexible and expandable way to represent and work with sensors. It enables the generation of different values for various tasks, making it suitable for diverse applications and use cases, including sensor data collection, modeling, or analysis.

// types.WithStart: Generation starts from the minimum value of 1 to 10
// types.WithEnd:   Generation ends at the minimum value from 10 to 1
// types.WithRandom: Data generation follows a Bezier curve from 1 to 10

minValue := 1
maxValue := 10
amplitude := 16 // 4 - 512

droneTracker.AddSensor("s1", minValue, maxValue, amplitude, types.WithStart|types.WithRandom|types.WithEnd)
droneTracker.AddSensor("s2", 10, 20, 16, types.WithRandom|types.WithEnd)
droneTracker.AddSensor("s3", 20, 30, 16, 0)

Generated Data

Device:
    id
    user_id
    tick
    duration
    model
    speed
    distance
    battery (charge, charge_time)
    routes (routes)
    location (lat, lon, elevation, bearing, lat_dms, lon_dms, utm)
    navigator (current_route_index, current_track_index, current_segment_index)
    sensors (id, name, val_x, val_y)
    description
    is_offline
    offline_duration
    color
    time_estimate
Device.Battery:
    charge
    charge_time
Device.Routes:
    routes (Route)
Device.Routes.Route:
    id
    tracks (Track)
    distance
    color
    props
    props_count
Device.Routes.Route.Track:
    distance
    num_segments
    color
    props
    props_count
Device.Sensor:
    id
    name
    val_x
    val_y
Device.Navigator:
    current_route_index
    current_track_index
    current_segment_index
Device.Distance:
    distance
    current_distance
    route_distance
    current_route_distance
    track_distance
    current_track_distance
    segment_distance
    current_segment_distance
Device.Location:
    lat
    lon
    elevation
    bearing
    lat_dms (degrees, minutes, seconds, direction)
    lon_dms (degrees, minutes, seconds, direction)
    utm (central_meridian, easting, northing, long_zone, lat_zone, hemisphere, srid)
Packet:
    devices (Device)
    timestamp

Documentation

Index

Constants

View Source
const (
	RouteLevelXS  = 1
	RouteLevelS   = 10
	RouteLevelM   = 60
	RouteLevelL   = 120
	RouteLevelXL  = 300
	RouteLevelXXL = 600
)

Route level constants define different levels of route complexity.

Variables

This section is empty.

Functions

func DecodeGPXRoutes added in v0.2.0

func DecodeGPXRoutes(data []byte) ([]*navigator.Route, error)

DecodeGPXRoutes decodes GPX data into a slice of navigator routes.

func DecodeGeoJSONRoutes added in v0.2.0

func DecodeGeoJSONRoutes(data []byte) ([]*navigator.Route, error)

DecodeGeoJSONRoutes decodes GeoJSON data into a slice of navigator routes.

func DecodeRoutes added in v0.2.0

func DecodeRoutes(data []byte) ([]*navigator.Route, error)

DecodeRoutes decodes binary data into a slice of navigator routes.

func DecodeSensors added in v0.2.0

func DecodeSensors(data []byte) ([]*types.Sensor, error)

DecodeSensors decodes binary data into a slice of Sensor types.

func EncodeGPXRoutes added in v0.2.0

func EncodeGPXRoutes(routes []*navigator.Route) ([]byte, error)

EncodeGPXRoutes encodes a slice of navigator routes into GPX format.

func EncodeGeoJSONRoutes added in v0.2.0

func EncodeGeoJSONRoutes(routes []*navigator.Route) ([]byte, error)

EncodeGeoJSONRoutes encodes a slice of navigator routes into GeoJSON format.

func EncodeRoutes added in v0.2.0

func EncodeRoutes(routes []*navigator.Route) ([]byte, error)

EncodeRoutes encodes a slice of navigator routes into binary data.

func EncodeSensors added in v0.2.0

func EncodeSensors(sensors []*types.Sensor) ([]byte, error)

EncodeSensors encodes a slice of Sensor types into binary data.

func EncodeTracker added in v0.2.0

func EncodeTracker(t *Device) ([]byte, error)

EncodeTracker encodes a Device into a binary format.

func PacketFromBytes

func PacketFromBytes(data []byte) (*pb.Packet, error)

PacketFromBytes decodes a byte slice into a protobuf Packet. Returns the decoded Packet and an error if decoding fails.

func RandomRoute

func RandomRoute(lon, lat float64, numTrack int, level int) *navigator.Route

RandomRoute generates a random route with specified parameters. The function generates tracks within the route, using a specified number of tracks and complexity level. The generated route is centered around the provided latitude and longitude. Returns a random route with tracks, or nil if an error occurs during track creation.

Types

type Device

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

Device represents a GPS tracking device with various capabilities.

func DecodeTracker added in v0.2.0

func DecodeTracker(data []byte) (*Device, error)

DecodeTracker decodes binary data into a Device.

func NewBicycleTracker

func NewBicycleTracker() *Device

NewBicycleTracker creates a new GPS tracking device.

func NewDevice

func NewDevice(opts *DeviceOptions) (*Device, error)

NewDevice creates a new GPS tracking device with the provided options.

func NewDogTracker

func NewDogTracker() *Device

NewDogTracker creates a new GPS tracking device.

func NewDroneTracker

func NewDroneTracker() *Device

NewDroneTracker creates a new GPS tracking device.

func NewKidsTracker

func NewKidsTracker() *Device

NewKidsTracker creates a new GPS tracking device.

func NewTracker

func NewTracker() *Device

NewTracker creates a new GPS tracking device.

func (*Device) AddRoute

func (d *Device) AddRoute(routes ...*navigator.Route) error

AddRoute adds one or more routes to the device's navigator.

func (*Device) AddSensor

func (d *Device) AddSensor(
	name string,
	min, max float64,
	amplitude int,
	mode types.SensorMode,
) (string, error)

AddSensor adds a sensor to the device with the specified parameters.

func (*Device) Color

func (d *Device) Color() string

Color returns the color of the device.

func (*Device) CurrentBearing

func (d *Device) CurrentBearing() float64

CurrentBearing returns the current bearing direction of the device.

func (*Device) CurrentDistance

func (d *Device) CurrentDistance() float64

CurrentDistance returns the distance traveled in the current segment.

func (*Device) CurrentRoute

func (d *Device) CurrentRoute() *navigator.Route

CurrentRoute returns the currently active route of the device.

func (*Device) CurrentRouteDistance

func (d *Device) CurrentRouteDistance() float64

CurrentRouteDistance returns the distance traveled in the current route.

func (*Device) CurrentSegment

func (d *Device) CurrentSegment() navigator.Segment

CurrentSegment returns the currently active segment of the device.

func (*Device) CurrentSegmentDistance

func (d *Device) CurrentSegmentDistance() float64

CurrentSegmentDistance returns the distance traveled in the current segment.

func (*Device) CurrentTrack

func (d *Device) CurrentTrack() *navigator.Track

CurrentTrack returns the currently active track of the device.

func (*Device) CurrentTrackDistance

func (d *Device) CurrentTrackDistance() float64

CurrentTrackDistance returns the distance traveled in the current track.

func (*Device) Descr

func (d *Device) Descr() string

func (*Device) DestinationTo

func (d *Device) DestinationTo(meters float64) bool

DestinationTo updates the device's position to a specified distance along the current segment. It returns true on success, indicating the update was applied.

func (*Device) Distance

func (d *Device) Distance() float64

Distance returns the total distance traveled by the device.

func (*Device) Duration

func (d *Device) Duration() float64

Duration returns the duration of the device's current track segment in seconds. It returns the duration of the current track segment or 0 if no track is active.

func (*Device) EachRoute

func (d *Device) EachRoute(fn func(int, *navigator.Route) bool)

EachRoute iterates over each route in the device's navigator and applies a function.

func (*Device) EachSensor

func (d *Device) EachSensor(fn func(int, *types.Sensor) bool)

EachSensor iterates over each sensor in the device's navigator and applies a function.

func (*Device) FromSnapshot

func (d *Device) FromSnapshot(snap *pb.Snapshot)

FromSnapshot updates the device's state using the provided snapshot data. It populates the device's state with the values from the snapshot, including device information, status, navigator, speed, battery, and sensors.

func (*Device) ID

func (d *Device) ID() string

ID returns the ID of the device.

func (*Device) IsFinish

func (d *Device) IsFinish() bool

IsFinish checks if the device has reached the end of its current route.

func (*Device) IsOffline

func (d *Device) IsOffline() bool

IsOffline returns whether the device is currently offline based on the navigator's status.

func (*Device) Location

func (d *Device) Location() geo.LatLonPoint

Location returns the current geographical location of the device.

func (*Device) MarshalBinary

func (d *Device) MarshalBinary() ([]byte, error)

MarshalBinary converts the device's current state into a binary representation. It creates a snapshot of the device and serializes it using protobuf encoding. Returns the binary representation of the device's state and an error, if any.

func (*Device) Model

func (d *Device) Model() string

Model returns the model of the device.

func (*Device) MoveToRoute

func (d *Device) MoveToRoute(routeIndex int) bool

MoveToRoute updates the device's position to a specific route. It returns true on success, indicating the update was applied.

func (*Device) MoveToRouteByID

func (d *Device) MoveToRouteByID(routeID string) bool

MoveToRouteByID updates the device's position to a specific route, identified by its ID. It returns true on success, indicating the update was applied.

func (*Device) MoveToSegment

func (d *Device) MoveToSegment(routeIndex int, trackIndex int, segmentIndex int) bool

MoveToSegment updates the device's position to a specific segment within a track and route. It returns true on success, indicating the update was applied.

func (*Device) MoveToTrack

func (d *Device) MoveToTrack(routeIndex int, trackIndex int) bool

MoveToTrack updates the device's position to a specific track within a route. It returns true on success, indicating the update was applied.

func (*Device) MoveToTrackByID

func (d *Device) MoveToTrackByID(routeID string, trackID string) bool

MoveToTrackByID updates the device's position to a specific track within a route, identified by IDs. It returns true on success, indicating the update was applied.

func (*Device) Next

func (d *Device) Next(tick float64) bool

Next advances the device's state for the next time step. The tick parameter represents the time interval in seconds since the last update. It updates the device's position, speed, elevation, battery level, sensors, and state. Returns true if the state was successfully updated, and false if no routes are available or if the navigator has finished.

func (*Device) NumRoutes

func (d *Device) NumRoutes() int

NumRoutes returns the number of routes stored in the device's navigator.

func (*Device) NumSensors

func (d *Device) NumSensors() int

NumSensors returns the number of sensors attached to the device.

func (*Device) RemoveRoute

func (d *Device) RemoveRoute(routeID string) bool

RemoveRoute removes a route from the device's navigator by its ID.

func (*Device) RemoveSensor

func (d *Device) RemoveSensor(sensorID string) (ok bool)

RemoveSensor removes a sensor with the specified sensorID from the device's list of sensors. It returns true if the sensor was successfully removed, and false otherwise. If the provided sensorID is empty, the function returns false.

func (*Device) RemoveTrack

func (d *Device) RemoveTrack(routeID, trackID string) bool

RemoveTrack removes a track from a route in the device's navigator.

func (*Device) ResetNavigator

func (d *Device) ResetNavigator()

ResetNavigator resets the navigator for the device. This method clears all navigation-related state and resets the device's position. It does not return a value.

func (*Device) ResetRoutes

func (d *Device) ResetRoutes() bool

ResetRoutes resets the routes associated with the device in the navigator. It returns true on success and updates the device's internal routes.

func (*Device) RouteAt

func (d *Device) RouteAt(index int) *navigator.Route

RouteAt returns the route at the specified index in the navigator. The index parameter is the index of the desired route. It returns the route at the given index or nil if the index is out of bounds.

func (*Device) RouteDistance

func (d *Device) RouteDistance() float64

RouteDistance returns the total distance of the active route.

func (*Device) RouteIndex

func (d *Device) RouteIndex() int

RouteIndex returns the index of the currently active route in the navigator.

func (*Device) SegmentDistance

func (d *Device) SegmentDistance() float64

SegmentDistance returns the total distance of the active segment.

func (*Device) SegmentIndex

func (d *Device) SegmentIndex() int

SegmentIndex returns the index of the current segment within the current track of the navigator.

func (*Device) SensorAt

func (d *Device) SensorAt(i int) *types.Sensor

SensorAt returns the sensor at the specified index from the device's navigator.

func (*Device) SensorByID

func (d *Device) SensorByID(sensorID string) (*types.Sensor, bool)

SensorByID returns the sensor with the given ID and a boolean indicating its existence.

func (*Device) SetColor

func (d *Device) SetColor(color colorful.Color) error

SetColor sets the color of the device.

func (*Device) SetDescription

func (d *Device) SetDescription(descr string)

SetDescription sets the description of the device.

func (*Device) SetModel

func (d *Device) SetModel(model string) error

SetModel sets the model of the device.

func (*Device) SetUserID

func (d *Device) SetUserID(id string) error

SetModel sets the model of the device.

func (*Device) Snapshot

func (d *Device) Snapshot() *pb.Snapshot

Snapshot creates and returns a snapshot of the device's current state. The snapshot includes device information, status, duration, navigator, speed, battery, and sensors (if any).

func (*Device) State

func (d *Device) State() *pb.Device

State returns a protobuf representation of the current device state.

func (*Device) Status

func (d *Device) Status() Status

Status returns the current status of the device.

func (*Device) ToNextRoute

func (d *Device) ToNextRoute() bool

ToNextRoute updates the device's position to the next route in the navigator. It returns true on success, indicating the update was applied.

func (*Device) ToOffline

func (d *Device) ToOffline()

ToOffline sets the device's status to offline in the navigator. This method does not return a value.

func (*Device) ToPrevRoute

func (d *Device) ToPrevRoute() bool

ToPrevRoute updates the device's position to the previous route in the navigator. It returns true on success, indicating the update was applied.

func (*Device) TrackDistance

func (d *Device) TrackDistance() float64

TrackDistance returns the total distance of the active track.

func (*Device) TrackIndex

func (d *Device) TrackIndex() int

TrackIndex returns the index of the currently active track in the navigator.

func (*Device) UnmarshalBinary

func (d *Device) UnmarshalBinary(data []byte) error

UnmarshalBinary populates the device's state using the provided binary data. It deserializes the binary data using protobuf decoding and updates the device's state accordingly. Returns an error if the binary data is invalid or if there's an issue during deserialization.

func (*Device) Update

func (d *Device) Update()

Update updates the device's state and routes based on its current navigator state.

func (*Device) UserID

func (d *Device) UserID() string

UserID returns the user ID associated with the device.

func (*Device) Version

func (d *Device) Version() [3]int

Version returns the current version of the device as an array of three integers. It retrieves the version from the device's navigator and returns it as [Navigator, Route, Track].

type DeviceOptions

type DeviceOptions struct {
	ID     string // ID of the device.
	Model  string // Model of the device.
	Color  string // Color of the device.
	UserID string // User ID associated with the device.
	Descr  string // Description of the device.

	Navigator struct {
		SkipOffline bool // Skip offline mode.
		Offline     struct {
			Min int // Minimum duration for offline mode.
			Max int // Maximum duration for offline mode.
		}
		Elevation struct {
			Min       float64          // Minimum elevation.
			Max       float64          // Maximum elevation.
			Amplitude int              // Amplitude for elevation changes.
			Mode      types.SensorMode // Sensor mode for elevation changes.
		}
	}

	Battery struct {
		Min        float64       // Minimum battery level.
		Max        float64       // Maximum battery level.
		ChargeTime time.Duration // Charging time for the battery.
	}

	Speed struct {
		Min       float64 // Minimum speed.
		Max       float64 // Maximum speed.
		Amplitude int     // Amplitude for speed changes.
	}
}

DeviceOptions defines the options for creating a new device.

func BicycleTrackerOptions

func BicycleTrackerOptions() *DeviceOptions

BicycleTrackerOptions returns DeviceOptions suitable for a bicycle tracker.

func DefaultTrackerOptions

func DefaultTrackerOptions() *DeviceOptions

DefaultTrackerOptions returns DeviceOptions suitable for a default tracker.

func DogTrackerOptions

func DogTrackerOptions() *DeviceOptions

DogTrackerOptions returns DeviceOptions suitable for a dog tracker.

func DroneTrackerOptions

func DroneTrackerOptions() *DeviceOptions

DroneTrackerOptions returns DeviceOptions suitable for a drone tracker.

func KidsTrackerOptions

func KidsTrackerOptions() *DeviceOptions

KidsTrackerOptions returns DeviceOptions suitable for a kids tracker.

func NewDeviceOptions

func NewDeviceOptions() *DeviceOptions

NewDeviceOptions creates a new set of default DeviceOptions.

type Generator

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

Generator represents the GPS data generator.

func New

func New(opts *Options) *Generator

New creates a new GPS data generator with the provided options.

func (*Generator) Attach

func (g *Generator) Attach(d *Device) error

Attach attaches the provided device to the generator.

func (*Generator) Close

func (g *Generator) Close()

Close stops the data generation process and closes the generator.

func (*Generator) Detach

func (g *Generator) Detach(deviceID string) error

Detach detaches a device with the given ID from the generator.

func (*Generator) Lookup

func (g *Generator) Lookup(deviceID string) (*Device, bool)

Lookup searches for a device with the given ID and returns it along with a boolean indicating its existence.

func (*Generator) NumDevices

func (g *Generator) NumDevices() int

NumDevices returns the number of devices attached to the generator.

func (*Generator) OnError

func (g *Generator) OnError(fn func(error))

OnError sets a callback function to handle errors during data generation.

func (*Generator) OnNext

func (g *Generator) OnNext(fn func())

OnNext sets a callback function to be executed at each "next step" of data generation.

func (*Generator) OnPacket

func (g *Generator) OnPacket(fn func([]byte))

OnPacket sets a callback function to handle generated data packets.

func (*Generator) Run

func (g *Generator) Run()

Run starts the data generation process using configured settings and attached devices.

type Options

type Options struct {
	// Interval determines the time interval between data generation iterations. Default one second.
	Interval time.Duration

	// PacketSize specifies the size of the data packet generated per iteration. Default 512.
	PacketSize int

	// NumWorkers sets the number of concurrent workers for data processing. Default numCPU.
	NumWorkers int
}

Options defines the configuration options for the Generator.

func NewOptions

func NewOptions() *Options

NewOptions creates a new Options instance with default values.

type Status

type Status byte

Status represents the status of a device.

const (
	Running Status = iota + 1
	Stopped
)

Running and Stopped are the possible values for the Status type.

Jump to

Keyboard shortcuts

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