spinix

package module
v0.0.0-...-b0a49f2 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2022 License: MIT Imports: 19 Imported by: 0

README

Spinix

GPS/GEO minimalist rules engine

Status

Work in progress ...

Documentation

Index

Constants

View Source
const (
	TinyRegionSize  RegionSize = 3
	SmallRegionSize RegionSize = 2
	LargeRegionSize RegionSize = 1

	TinyRegionThreshold  = 50000  // meters
	SmallRegionThreshold = 100000 // meters
	LargeRegionThreshold = 300000 // meters
)

Variables

View Source
var DefaultLayer = xid.NilID()
View Source
var ErrDeviceNotFound = errors.New("spinix/devices: not found")
View Source
var ErrObjectNotFound = errors.New("spinix/objects: not found")
View Source
var ErrRuleNotFound = errors.New("spinix/rule: rule not found")
View Source
var ErrStateNotFound = errors.New("spinix/states:  not found")

Functions

func H3IndexFromLatLon

func H3IndexFromLatLon(lat, lon float64, rs RegionSize) h3.H3Index

func NewMemoryState

func NewMemoryState() *memoryState

func Walk

func Walk(v Visitor, node Expr)

func WalkFunc

func WalkFunc(node Expr, fn func(Expr))

Types

type AfterDetectFunc

type AfterDetectFunc func(device *Device, rule *Rule, match bool, events []Event)

type BaseLit

type BaseLit struct {
	Kind Token
	Expr Expr
	Pos  Pos
}

func (*BaseLit) String

func (e *BaseLit) String() string

type BeforeDetectFunc

type BeforeDetectFunc func(device *Device, rule *Rule) bool

type BinaryExpr

type BinaryExpr struct {
	LHS Expr  // left operand
	Op  Token // operator
	RHS Expr  // right operand
}

A BinaryExpr nodes represents a binary expression.

func (*BinaryExpr) String

func (e *BinaryExpr) String() string

type BooleanLit

type BooleanLit struct {
	Value bool
	Pos   Pos
}

A BooleanLit represents a boolean literal.

func (*BooleanLit) String

func (e *BooleanLit) String() string

type Decl

type Decl struct {
	Keyword Token
	Refs    []xid.ID
}

type Detector

type Detector interface {
	Detect(ctx context.Context, device *Device) ([]Event, bool, error)
}

type Device

type Device struct {
	ID            DeviceID `json:"id"`
	Layer         LayerID  `json:"layerId"`
	IMEI          string   `json:"imei"`
	Owner         string   `json:"owner"`
	Brand         string   `json:"brand"`
	Model         string   `json:"model"`
	Latitude      float64  `json:"lat"`
	Longitude     float64  `json:"lon"`
	Altitude      float64  `json:"alt"`
	Speed         float64  `json:"speed"`
	DateTime      int64    `json:"dateTime"`
	Status        int      `json:"status"`
	BatteryCharge float64  `json:"batteryCharge"`
	Temperature   float64  `json:"temperature"`
	Humidity      float64  `json:"humidity"`
	Luminosity    float64  `json:"luminosity"`
	Pressure      float64  `json:"pressure"`
	FuelLevel     float64  `json:"fuelLevel"`
	// contains filtered or unexported fields
}

func (*Device) DetectRegion

func (d *Device) DetectRegion()

func (*Device) RegionID

func (d *Device) RegionID() RegionID

func (*Device) RegionSize

func (d *Device) RegionSize() RegionSize

func (*Device) ResetRegion

func (d *Device) ResetRegion()

type DeviceID

type DeviceID = xid.ID

type DeviceIterFunc

type DeviceIterFunc func(ctx context.Context, d *Device) error

type DeviceLit

type DeviceLit struct {
	Unit  DistanceUnit
	Kind  Token
	Value float64
	Pos   Pos
}

func (*DeviceLit) String

func (e *DeviceLit) String() string

type Devices

type Devices interface {
	Lookup(ctx context.Context, id DeviceID) (*Device, error)
	InsertOrReplace(ctx context.Context, device *Device) (bool, error)
	Delete(ctx context.Context, id DeviceID) error
	Each(ctx context.Context, rid RegionID, size RegionSize, fn DeviceIterFunc) error
	Near(ctx context.Context, lat, lon, meters float64, fn DeviceIterFunc) error
}

func NewMemoryDevices

func NewMemoryDevices() Devices

type DevicesLit

type DevicesLit struct {
	All   bool
	Unit  DistanceUnit
	Kind  Token
	Value float64
	Pos   Pos
	Ref   []xid.ID
}

func (*DevicesLit) String

func (e *DevicesLit) String() string

type DistanceLit

type DistanceLit struct {
	Unit  DistanceUnit
	Value float64
	Pos   Pos
}

func (*DistanceLit) String

func (e *DistanceLit) String() string

type DistanceUnit

type DistanceUnit int
const (
	DistanceUndefined  DistanceUnit = 0
	DistanceMeters     DistanceUnit = 1
	DistanceKilometers DistanceUnit = 2
)

func (DistanceUnit) String

func (u DistanceUnit) String() string

type DurationLit

type DurationLit struct {
	Kind  Token
	Value time.Duration
	Pos   Pos
}

func (*DurationLit) String

func (e *DurationLit) String() string

type Engine

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

func New

func New(opts ...Option) *Engine

func (*Engine) AddRule

func (e *Engine) AddRule(ctx context.Context, spec string) (*Rule, error)

func (*Engine) AssignCoordsFromSpec

func (e *Engine) AssignCoordsFromSpec(ctx context.Context, rule *Rule) (err error)

func (*Engine) Detect

func (e *Engine) Detect(ctx context.Context, device *Device) (events []Event, ok bool, err error)

func (*Engine) Devices

func (e *Engine) Devices() Devices

func (*Engine) Objects

func (e *Engine) Objects() Objects

func (*Engine) Rules

func (e *Engine) Rules() Rules

func (*Engine) States

func (e *Engine) States() States

type Event

type Event struct {
	ID       string       `json:"ID"`
	Device   Device       `json:"device"`
	DateTime int64        `json:"dateTime"`
	Rule     RuleSnapshot `json:"rule"`
	Match    []Match      `json:"match"`
}

func MakeEvent

func MakeEvent(d *Device, r *Rule, m []Match) Event

type Expr

type Expr interface {
	String() string
	// contains filtered or unexported methods
}

func ParseSpec

func ParseSpec(spec string) (Expr, error)

type FloatLit

type FloatLit struct {
	Value float64
	Pos   Pos
}

A FloatLit nodes represents a literal of float type.

func (FloatLit) String

func (e FloatLit) String() string

type GeoObject

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

func NewGeoObject

func NewGeoObject(oid ObjectID, lid LayerID, data geojson.Object) *GeoObject

func NewGeoObjectWithID

func NewGeoObjectWithID(lid LayerID, data geojson.Object) *GeoObject

func (*GeoObject) Boundary

func (o *GeoObject) Boundary() geometry.Rect

func (*GeoObject) Center

func (o *GeoObject) Center() geometry.Point

func (*GeoObject) Contains

func (o *GeoObject) Contains(other *GeoObject) bool

func (*GeoObject) Data

func (o *GeoObject) Data() geojson.Object

func (*GeoObject) ID

func (o *GeoObject) ID() ObjectID

func (*GeoObject) Intersects

func (o *GeoObject) Intersects(other *GeoObject) bool

func (*GeoObject) Layer

func (o *GeoObject) Layer() LayerID

func (*GeoObject) RegionID

func (o *GeoObject) RegionID() []RegionID

func (*GeoObject) RegionSize

func (o *GeoObject) RegionSize() RegionSize

func (*GeoObject) Within

func (o *GeoObject) Within(other *GeoObject) bool

type IDLit

type IDLit struct {
	Kind  Token
	Value xid.ID
	Pos   Pos
}

func (*IDLit) String

func (e *IDLit) String() string

type IdentLit

type IdentLit struct {
	Name string
	Pos  Pos
	Kind Token
}

An IdentLit nodes represents an identifier.

func (*IdentLit) String

func (e *IdentLit) String() string

type IntLit

type IntLit struct {
	Value int
	Pos   Pos
}

An IntLit nodes represents a literal of int type.

func (*IntLit) String

func (e *IntLit) String() string

type InvalidExprError

type InvalidExprError struct {
	Left  Expr
	Right Expr
	Op    Token
	Msg   string
	Pos   Pos
}

func (*InvalidExprError) Error

func (e *InvalidExprError) Error() string

type LayerID

type LayerID = xid.ID

type ListLit

type ListLit struct {
	Items []Expr
	Pos   Pos
	Kind  Token
	Typ   Token
}

A ListLit represents a list of int or float or string type.

func (*ListLit) String

func (e *ListLit) String() string

type Match

type Match struct {
	Ok       bool  `json:"ok"`
	Left     Decl  `json:"left"`
	Right    Decl  `json:"right"`
	Operator Token `json:"operator"`
	Pos      Pos   `json:"pos"`
}

type Object

type Object struct {
	ID   string
	Data geojson.Object
}

type ObjectID

type ObjectID = xid.ID

type ObjectIterFunc

type ObjectIterFunc func(ctx context.Context, o *GeoObject) error

type ObjectLit

type ObjectLit struct {
	All    bool
	Kind   Token
	Ref    []xid.ID
	DurVal time.Duration
	DurTyp Token
	Pos    Pos
}

func (*ObjectLit) String

func (e *ObjectLit) String() string

type Objects

type Objects interface {
	Lookup(ctx context.Context, oid ObjectID) (*GeoObject, error)
	Add(ctx context.Context, o *GeoObject) error
	Delete(ctx context.Context, oid ObjectID) error
	Each(ctx context.Context, lid LayerID, rid RegionID, fn ObjectIterFunc) error
	Near(ctx context.Context, lid LayerID, lat, lon, meters float64, fn ObjectIterFunc) error
}

func NewMemoryObjects

func NewMemoryObjects() Objects

type Option

type Option func(*Engine)

func WithDetectAfter

func WithDetectAfter(fn ...AfterDetectFunc) Option

func WithDetectBefore

func WithDetectBefore(fn ...BeforeDetectFunc) Option

func WithDevicesStorage

func WithDevicesStorage(d Devices) Option

func WithObjectsStorage

func WithObjectsStorage(o Objects) Option

func WithRulesStorage

func WithRulesStorage(r Rules) Option

func WithStatesStorage

func WithStatesStorage(s States) Option

type ParenExpr

type ParenExpr struct {
	Expr Expr // parenthesized expression
}

A ParenExpr nodes represents a parenthesized expression.

func (*ParenExpr) String

func (e *ParenExpr) String() string

type Parser

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

func (*Parser) Parse

func (p *Parser) Parse() (Expr, error)

type ParserError

type ParserError struct {
	Tok Token
	Lit string
	Pos Pos
	Msg string
}

func (*ParserError) Error

func (e *ParserError) Error() string

type PointLit

type PointLit struct {
	Lat, Lon float64
	Pos      Pos
	Kind     Token
}

func (*PointLit) String

func (e *PointLit) String() string

type Pos

type Pos int

type PropExpr

type PropExpr struct {
	Expr Expr
	List []Expr
}

func (*PropExpr) String

func (e *PropExpr) String() string

type Region

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

func MakeRegion

func MakeRegion(id RegionID, size RegionSize) Region

func (Region) Bounding

func (r Region) Bounding() []geometry.Point

func (Region) Center

func (r Region) Center() geometry.Point

func (Region) ID

func (r Region) ID() RegionID

func (Region) Size

func (r Region) Size() RegionSize

func (Region) String

func (r Region) String() string

type RegionID

type RegionID uint64

func RegionFromLatLon

func RegionFromLatLon(lat, lon float64, rs RegionSize) RegionID

func RegionIDFromString

func RegionIDFromString(id string) (RegionID, error)

func RegionIDs

func RegionIDs(points []geometry.Point, rs RegionSize) []RegionID

func (RegionID) Size

func (rid RegionID) Size() RegionSize

func (RegionID) String

func (rid RegionID) String() string

type RegionSize

type RegionSize int

func RegionSizeFromMeters

func RegionSizeFromMeters(value float64) RegionSize

func (RegionSize) IsLarge

func (rs RegionSize) IsLarge() bool

func (RegionSize) IsSmall

func (rs RegionSize) IsSmall() bool

func (RegionSize) IsTiny

func (rs RegionSize) IsTiny() bool

func (RegionSize) String

func (rs RegionSize) String() string

func (RegionSize) Threshold

func (rs RegionSize) Threshold() float64

func (RegionSize) Validate

func (rs RegionSize) Validate() (err error)

func (RegionSize) Value

func (rs RegionSize) Value() int

type RepeatMode

type RepeatMode int
const (
	RepeatOnce  RepeatMode = 1
	RepeatEvery RepeatMode = 2
	RepeatTimes RepeatMode = 3
)

func (RepeatMode) String

func (rm RepeatMode) String() string

type ResetLit

type ResetLit struct {
	Kind  Token
	Pos   Pos
	After time.Duration
}

func (*ResetLit) String

func (e *ResetLit) String() string

type Rule

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

func NewRule

func NewRule(spec string) (*Rule, error)

func RuleFromSpec

func RuleFromSpec(id xid.ID, regions []RegionID, size RegionSize, spec string) (*Rule, error)

func (*Rule) Bounding

func (r *Rule) Bounding() geometry.Rect

func (*Rule) Center

func (r *Rule) Center() geometry.Point

func (*Rule) ID

func (r *Rule) ID() RuleID

func (*Rule) MarshalJSON

func (r *Rule) MarshalJSON() ([]byte, error)

func (*Rule) RefIDs

func (r *Rule) RefIDs() (refs map[xid.ID]Token)

func (*Rule) RegionIDs

func (r *Rule) RegionIDs() (ids []RegionID)

func (*Rule) RegionSize

func (r *Rule) RegionSize() RegionSize

func (*Rule) Regions

func (r *Rule) Regions() []Region

func (*Rule) Snapshot

func (r *Rule) Snapshot() RuleSnapshot

func (*Rule) Specification

func (r *Rule) Specification() string

func (*Rule) UnmarshalJSON

func (r *Rule) UnmarshalJSON(data []byte) (err error)

type RuleID

type RuleID = xid.ID

type RuleIterFunc

type RuleIterFunc func(ctx context.Context, rule *Rule, err error) error

type RuleSnapshot

type RuleSnapshot struct {
	RuleID     string   `json:"ID"`
	Spec       string   `json:"spec"`
	RegionIDs  []string `json:"RegionIDs"`
	RegionSize int      `json:"regionSize"`
}

type Rules

type Rules interface {
	Walk(ctx context.Context, lat float64, lon float64, fn RuleIterFunc) error
	Insert(ctx context.Context, r *Rule) error
	Delete(ctx context.Context, id RuleID) error
	Lookup(ctx context.Context, id RuleID) (*Rule, error)
}

func NewMemoryRules

func NewMemoryRules() Rules

type Scanner

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

func NewScanner

func NewScanner(r io.Reader) *Scanner

func (*Scanner) Next

func (s *Scanner) Next() (tok Token, lit string)

func (*Scanner) NextLit

func (s *Scanner) NextLit() string

func (*Scanner) NextTok

func (s *Scanner) NextTok() Token

func (*Scanner) Offset

func (s *Scanner) Offset() Pos

func (*Scanner) Reset

func (s *Scanner) Reset()

func (*Scanner) Scan

func (s *Scanner) Scan() (rune, string)

type State

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

func NewState

func NewState(id StateID) *State

func (*State) DeviceID

func (s *State) DeviceID() DeviceID

func (*State) FromSnapshot

func (s *State) FromSnapshot(snap StateSnapshot)

func (*State) HitIncr

func (s *State) HitIncr()

func (*State) Hits

func (s *State) Hits() int

func (*State) ID

func (s *State) ID() StateID

func (*State) LastResetTime

func (s *State) LastResetTime() int64

func (*State) LastSeenTime

func (s *State) LastSeenTime() int64

func (*State) LastVisit

func (s *State) LastVisit(objectID string) int64

func (*State) NeedReset

func (s *State) NeedReset(interval time.Duration) bool

func (*State) Reset

func (s *State) Reset()

func (*State) RuleID

func (s *State) RuleID() RuleID

func (*State) SetLastVisit

func (s *State) SetLastVisit(objectID string, visit int64)

func (*State) SetTime

func (s *State) SetTime(now int64)

func (*State) Snapshot

func (s *State) Snapshot() StateSnapshot

func (*State) UpdateLastResetTime

func (s *State) UpdateLastResetTime()

func (*State) UpdateLastSeenTime

func (s *State) UpdateLastSeenTime()

type StateID

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

func (StateID) String

func (s StateID) String() string

type StateSnapshot

type StateSnapshot struct {
	ID            StateID          `json:"ID"`
	Now           int64            `json:"now"`
	LastSeenTime  int64            `json:"lastSeenTime"`
	LastResetTime int64            `json:"lastResetTime"`
	Hits          int              `json:"hits"`
	ObjectsVisits map[string]int64 `json:"objectsVisits"`
}

func (StateSnapshot) MarshalJSON

func (s StateSnapshot) MarshalJSON() ([]byte, error)

func (*StateSnapshot) UnmarshalJSON

func (s *StateSnapshot) UnmarshalJSON(data []byte) error

type States

type States interface {
	Lookup(ctx context.Context, id StateID) (*State, error)
	Update(ctx context.Context, s *State) error
	Make(ctx context.Context, id StateID) (*State, error)
	Remove(ctx context.Context, id StateID) error
	RemoveByRule(ctx context.Context, rid RuleID) error
	RemoveByDevice(ctx context.Context, did DeviceID) error
}

type StringLit

type StringLit struct {
	Value string
	Pos   Pos
}

A StringLit nodes represents a literal of string type.

func (*StringLit) String

func (e *StringLit) String() string

type TimeLit

type TimeLit struct {
	Hour   int
	Minute int
	Pos    Pos
}

A TimeLit nodes represents a literal of time type.

func (*TimeLit) String

func (e *TimeLit) String() string

type Token

type Token int
const (
	ILLEGAL Token = iota
	EOF

	IDENT          // operation
	INT            // 12345
	FLOAT          // 123.45
	STRING         // "abc"
	DEVICE         // device
	RADIUS         // radius
	BBOX           // bbox
	TIME           // time
	DURATION       // duration
	AFTER          // after
	FUELLEVEL      // fuellevel
	PRESSURE       // pressure
	LUMINOSITY     // luminosity
	HUMIDITY       // humidity
	TEMPERATURE    // temperature
	BATTERY_CHARGE // batteryCharge
	STATUS         // status
	SPEED          // speed
	MODEL          // model
	BRAND          // brand
	OWNER          // owner
	LAYER          // layer
	IMEI           // imei
	VAR_IDENT      // @
	YEAR           // year
	MONTH          // month
	WEEK           // week
	DAY            // day
	HOUR           // hour
	DATE           // date
	DATETIME       // dateTime
	TRIGGER        // trigger
	CENTER         // center
	EXPIRE         // expire
	RESET          // reset

	AND //  AND
	OR  //  OR

	IN          // IN
	NIN         // NOT IN
	RANGE       // RANGE
	NRANGE      // NOT RANGE
	NEAR        // NEAR
	NNEAR       // NOT NEAR
	INTERSECTS  // INTERSECTS
	NINTERSECTS // NOT INTERSECTS

	SUB // -
	EQ  // eq  i.e. ==
	LT  // lt  i.e. <
	GT  // gt  i.e. >
	NE  // ne  i.e. !=
	LTE // lte i.e. <=
	GTE // gte i.e. >=

	LBRACK // [
	LBRACE // {
	COMMA  // ,
	PERIOD // .

	RBRACK // ]
	RBRACE // }
	COLON  // :

	DEVICES        // devices(@ID)
	OBJECTS        // object(@ID, @id1)
	POLY           // polygon(@id1, @id2, @id3), poly(@ID)
	MULTI_POLY     // multiPolygon(@id1, @id2)
	LINE           // line(@id1, @id2)
	MULTI_LINE     // multiLine(@id1, @id2)
	POINT          // point(@ID)
	MULTI_POINT    // multiPoint(@ID)
	RECT           // rect(@ID)
	CIRCLE         // circle(@ID)
	COLLECTION     // collection(@ID)
	FUT_COLLECTION // featureCollection(@id1, @id2, @id3)

	RPAREN // )
	LPAREN // (
)

func LookupKeyword

func LookupKeyword(ident string) (tok Token, found bool)

func (Token) IsGeospatial

func (tok Token) IsGeospatial() bool

func (Token) IsKeyword

func (tok Token) IsKeyword() bool

func (Token) IsLiteral

func (tok Token) IsLiteral() bool

func (Token) IsOperator

func (tok Token) IsOperator() bool

func (Token) Precedence

func (tok Token) Precedence() int

func (Token) String

func (tok Token) String() string

type TriggerLit

type TriggerLit struct {
	Repeat   RepeatMode
	Interval time.Duration
	Value    time.Duration
	Times    int
	Pos      Pos
}

A TriggerLit represents a repeat mode type.

func (*TriggerLit) String

func (e *TriggerLit) String() string

type VarLit

type VarLit struct {
	Value Token
	Pos   Pos
}

A VarLit represents a variable literal.

func (*VarLit) String

func (e *VarLit) String() string

type Visitor

type Visitor interface {
	Visit(Expr) Visitor
}

Directories

Path Synopsis
cmd
gen
internal
mocks
tracker
Package mocktracker is a generated GoMock package.
Package mocktracker is a generated GoMock package.

Jump to

Keyboard shortcuts

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