codec

package
v0.0.0-...-55fa497 Latest Latest
Warning

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

Go to latest
Published: May 26, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrCodecNotFound is returned when a codec is not found
	ErrCodecNotFound = errors.New("codec not found")
	// ErrInvalidCodecFormat is returned when codec validation fails
	ErrInvalidCodecFormat = errors.New("invalid codec format")
)
View Source
var (
	// ErrInvalidScript is returned when the JavaScript code is invalid
	ErrInvalidScript = errors.New("invalid JavaScript code")
	// ErrOnUplinkNotFound is returned when OnUplink function is not defined
	ErrOnUplinkNotFound = errors.New("OnUplink function not found")
	// ErrInvalidReturnType is returned when the codec returns an invalid type
	ErrInvalidReturnType = errors.New("invalid return type from codec")
	// ErrExecutionTimeout is returned when codec execution exceeds the configured timeout
	ErrExecutionTimeout = errors.New("codec execution timeout")
)

Functions

func CreateAM319Codec

func CreateAM319Codec() string

CreateAM319Codec returns the Milesight AM319 codec script

func CreateMCFLW13IOCodec

func CreateMCFLW13IOCodec() string

CreateMCFLW13IOCodec returns the Enginko MCF-LW13IO I/O Controller codec script

func CreateSDM230Codec

func CreateSDM230Codec() string

CreateSDM230Codec returns the Eastron SDM230 energy meter codec script

func InjectConversionHelpers

func InjectConversionHelpers(vm *goja.Runtime) error

InjectConversionHelpers injects payload conversion helper functions into the JavaScript VM These allow explicit conversion from hex/base64 strings to byte arrays

func InjectDeviceHelpers

func InjectDeviceHelpers(vm *goja.Runtime, device DeviceInterface) error

InjectDeviceHelpers injects device configuration helper functions into the JavaScript VM These allow JavaScript codecs to read and modify device settings

func InjectStateHelpers

func InjectStateHelpers(vm *goja.Runtime, state *State) error

InjectStateHelpers injects state management helper functions into the JavaScript VM Simplified to only include getState and setState (all-purpose state management)

Types

type Codec

type Codec struct {
	ID     int    `json:"id"`     // Unique identifier (sequential)
	Name   string `json:"name"`   // Human-readable name
	Script string `json:"script"` // JavaScript code
}

Codec represents a JavaScript codec for encoding/decoding device payloads Compatible with ChirpStack codec format

func NewCodec

func NewCodec(name, script string) *Codec

NewCodec creates a new codec (ID must be set by the registry)

func (*Codec) Clone

func (c *Codec) Clone() *Codec

Clone creates a deep copy of the codec

func (*Codec) Metadata

func (c *Codec) Metadata() CodecMetadata

Metadata returns metadata without the script

func (*Codec) Validate

func (c *Codec) Validate() error

Validate checks if the codec is valid

type CodecLibrary

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

CodecLibrary manages a collection of codecs

func NewCodecLibrary

func NewCodecLibrary() *CodecLibrary

NewCodecLibrary creates a new codec library

func (*CodecLibrary) Add

func (cl *CodecLibrary) Add(codec *Codec) error

Add adds a codec to the library with the next available ID

func (*CodecLibrary) Clear

func (cl *CodecLibrary) Clear()

Clear removes all codecs

func (*CodecLibrary) Count

func (cl *CodecLibrary) Count() int

Count returns the number of codecs

func (*CodecLibrary) FromJSON

func (cl *CodecLibrary) FromJSON(data []byte) error

FromJSON deserializes a codec library from JSON

func (*CodecLibrary) Get

func (cl *CodecLibrary) Get(id int) (*Codec, error)

Get retrieves a codec by ID

func (*CodecLibrary) GetNextID

func (cl *CodecLibrary) GetNextID() int

GetNextID returns the next ID that will be assigned

func (*CodecLibrary) List

func (cl *CodecLibrary) List() []CodecMetadata

List returns all codec metadata

func (*CodecLibrary) LoadDefaults

func (cl *CodecLibrary) LoadDefaults()

LoadDefaults loads default example codecs with sequential IDs

func (*CodecLibrary) Remove

func (cl *CodecLibrary) Remove(id int) error

Remove removes a codec from the library

func (*CodecLibrary) SetNextID

func (cl *CodecLibrary) SetNextID(id int)

SetNextID sets the next ID to assign

func (*CodecLibrary) ToJSON

func (cl *CodecLibrary) ToJSON() ([]byte, error)

ToJSON serializes the codec library to JSON

func (*CodecLibrary) Update

func (cl *CodecLibrary) Update(id int, name string, script string) error

Update updates an existing codec by ID, preserving the original ID

type CodecMetadata

type CodecMetadata struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

CodecMetadata holds metadata about a codec without the script

type DeviceInterface

type DeviceInterface interface {
	GetSendInterval() time.Duration
	SetSendInterval(time.Duration)
	Print(content string, err error, printType int)
}

DeviceInterface defines the interface for accessing device configuration from JavaScript

type Executor

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

Executor manages JavaScript codec execution with goja

func NewExecutor

func NewExecutor(config *ExecutorConfig) *Executor

NewExecutor creates a new codec executor

func (*Executor) Close

func (e *Executor) Close()

Close closes the executor and releases resources

func (*Executor) ExecuteDecode

func (e *Executor) ExecuteDecode(script string, bytes []byte, fPort uint8, state *State, device DeviceInterface) error

ExecuteDecode executes the OnDownlink function from a JavaScript codec Parameters:

  • script: The JavaScript code containing the OnDownlink function
  • bytes: The byte array to decode
  • fPort: The LoRaWAN fPort
  • state: Device state for stateful decoding
  • device: Device interface for accessing configuration

OnDownlink is executed for its side effects (log, setState, setSendInterval). Any return value from the JavaScript function is ignored.

func (*Executor) ExecuteEncode

func (e *Executor) ExecuteEncode(script string, state *State, device DeviceInterface) ([]byte, uint8, error)

ExecuteEncode executes the OnUplink function from a JavaScript codec Parameters:

  • script: The JavaScript code containing the OnUplink function
  • state: Device state for stateful encoding
  • device: Device interface for accessing configuration (send interval, etc.)

Returns the encoded byte array, the fPort (from device or codec), and any error

func (*Executor) GetMetrics

func (e *Executor) GetMetrics() ExecutorMetrics

GetMetrics returns current executor metrics

func (*Executor) ResetMetrics

func (e *Executor) ResetMetrics()

ResetMetrics resets all metrics to zero

type ExecutorConfig

type ExecutorConfig struct {
	MaxVMs        int
	EnableMetrics bool
	TimeoutMs     int
}

ExecutorConfig holds configuration for the Executor

func DefaultExecutorConfig

func DefaultExecutorConfig() *ExecutorConfig

DefaultExecutorConfig returns default configuration

type ExecutorMetrics

type ExecutorMetrics struct {
	TotalExecutions uint64
	TotalErrors     uint64
	TotalTimeouts   uint64
	// contains filtered or unexported fields
}

ExecutorMetrics tracks codec execution statistics

type Registry

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

Registry manages codecs and device states for the entire simulator

func NewRegistry

func NewRegistry(config *ExecutorConfig) *Registry

NewRegistry creates a new codec registry

func (*Registry) AddCodec

func (r *Registry) AddCodec(codec *Codec) error

AddCodec adds a codec to the library

func (*Registry) Close

func (r *Registry) Close()

Close closes the registry and releases resources

func (*Registry) DecodePayload

func (r *Registry) DecodePayload(codecID int, devEUI string, bytes []byte, fPort uint8, device DeviceInterface) error

DecodePayload executes the OnDownlink function from a codec Parameters:

  • codecID: ID of the codec to use
  • devEUI: Device EUI for state management
  • bytes: Bytes to decode
  • fPort: LoRaWAN fPort
  • device: Device interface for accessing configuration

OnDownlink is executed for its side effects (log, setState, setSendInterval).

func (*Registry) EncodePayload

func (r *Registry) EncodePayload(codecID int, devEUI string, device DeviceInterface) ([]byte, uint8, error)

EncodePayload encodes a payload using a codec Parameters:

  • codecID: ID of the codec to use
  • devEUI: Device EUI for state management
  • device: Device interface for accessing configuration (send interval, etc.)

Returns the encoded bytes, actual fPort (from codec or device), and any error

func (*Registry) GetCodec

func (r *Registry) GetCodec(id int) (*Codec, error)

GetCodec retrieves a codec by ID

func (*Registry) GetCodecCount

func (r *Registry) GetCodecCount() int

GetCodecCount returns the number of codecs in the library

func (*Registry) GetCodecIDByName

func (r *Registry) GetCodecIDByName(name string) int

GetCodecIDByName returns the ID of a codec by its name, or 0 if not found

func (*Registry) GetNextID

func (r *Registry) GetNextID() int

GetNextID returns the next ID that will be assigned

func (*Registry) GetOrCreateState

func (r *Registry) GetOrCreateState(devEUI string) *State

GetOrCreateState gets or creates a state for a device

func (*Registry) ListCodecs

func (r *Registry) ListCodecs() []CodecMetadata

ListCodecs returns all codec metadata

func (*Registry) Load

func (r *Registry) Load(filepath string) error

Load loads the codec library from a file If the file doesn't exist or loading fails, it loads defaults instead

func (*Registry) LoadDefaults

func (r *Registry) LoadDefaults()

LoadDefaults loads default codecs into the library

func (*Registry) LoadStates

func (r *Registry) LoadStates(filepath string) error

LoadStates replaces the in-memory state map with the contents of the given file. Missing file is non-fatal and leaves the map empty.

func (*Registry) RemoveCodec

func (r *Registry) RemoveCodec(id int) error

RemoveCodec removes a codec from the library

func (*Registry) RemoveState

func (r *Registry) RemoveState(devEUI string)

RemoveState removes the persisted state for a device (e.g. on device deletion)

func (*Registry) Save

func (r *Registry) Save(filepath string) error

Save saves the codec library to a file

func (*Registry) SaveStates

func (r *Registry) SaveStates(filepath string) error

SaveStates writes per-device codec state to disk as a JSON map keyed by DevEUI.

func (*Registry) UpdateCodec

func (r *Registry) UpdateCodec(id int, name string, script string) error

UpdateCodec updates an existing codec by ID

type State

type State struct {
	DevEUI    string                 `json:"devEUI"`
	Variables map[string]interface{} `json:"variables"`
	CreatedAt time.Time              `json:"createdAt"`
	UpdatedAt time.Time              `json:"updatedAt"`
	// contains filtered or unexported fields
}

State holds the runtime state for a device's codec execution

func NewState

func NewState(devEUI string) *State

NewState creates a new State instance for a device

func (*State) GetVariable

func (s *State) GetVariable(name string) interface{}

GetVariable returns the value of a variable (nil if not set)

func (*State) SetVariable

func (s *State) SetVariable(name string, value interface{})

SetVariable sets the value of a variable

type VMPool

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

VMPool manages a pool of goja VMs for reuse

func NewVMPool

func NewVMPool(size int) *VMPool

NewVMPool creates a new VM pool with the specified size. All VMs are pre-created and callers block until one is available.

func (*VMPool) Available

func (p *VMPool) Available() int

Available returns the number of VMs currently available in the pool

func (*VMPool) Close

func (p *VMPool) Close()

Close closes the pool and releases all VMs

func (*VMPool) Get

func (p *VMPool) Get() *goja.Runtime

Get retrieves a VM from the pool, blocking until one is available.

func (*VMPool) Put

func (p *VMPool) Put(vm *goja.Runtime)

Put returns a VM to the pool after clearing its state.

func (*VMPool) Size

func (p *VMPool) Size() int

Size returns the maximum size of the pool

Jump to

Keyboard shortcuts

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