script

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

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

Go to latest
Published: May 5, 2026 License: MPL-2.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Errors []string = []string{
	"crashed",
	"syntax_error",
	"reference_error",
	"type_error",
	"out_of_memory",
	"out_of_codespace",
	"internal_error",
	"not_implemented",
	"file_read_error",
	"bad_arguments",
}

Functions

func Download

func Download(ctx context.Context, via types.Channel, device types.Device, name string, id uint32) (string, error)

func EnableDisable

func EnableDisable(ctx context.Context, via types.Channel, device types.Device, name string, enable bool) (any, error)

func EvalInDevice

func EvalInDevice(ctx context.Context, via types.Channel, device types.Device, name string, code string) (any, error)

func Init

func Init(l logr.Logger, r types.MethodsRegistrar)

Init registers the script.* method handlers. To use ReadEmbeddedFile or the embedded-script path of Upload/Run, the caller must also call SetFS() with an fs.FS containing the scripts.

func ListAvailable

func ListAvailable() ([]string, error)

func NewEventsHandler

func NewEventsHandler(ctx context.Context, vm *goja.Runtime) *eventsHandler

func ReadEmbeddedFile

func ReadEmbeddedFile(name string) ([]byte, error)

ReadEmbeddedFile reads an embedded script file by name

func Run

func Run(ctx context.Context, name string, buf []byte, minify bool) error

func RunWithDeviceFile

func RunWithDeviceFile(ctx context.Context, name string, buf []byte, minify bool, deviceFile string) error

RunWithDeviceFile runs a Shelly script with device state persistence

func RunWithDeviceState

func RunWithDeviceState(ctx context.Context, name string, buf []byte, minify bool, deviceState *DeviceState) error

RunWithDeviceState runs a script with a provided device state for testing

func SaveDeviceState

func SaveDeviceState(log logr.Logger, filename string, state *DeviceState) error

SaveDeviceState saves device state to a JSON file with indentation

func SetFS

func SetFS(scriptsFS fs.FS)

SetFS sets the filesystem from which embedded scripts are read by ReadEmbeddedFile and by the buf-empty branches of Upload/Run.

func StartStopDelete

func StartStopDelete(ctx context.Context, via types.Channel, device types.Device, name string, operation Verb) (any, error)

func Upload

func Upload(ctx context.Context, via types.Channel, device types.Device, name string, code []byte, minify bool) (uint32, error)

For MyHome-specific version tracking, use internal/myhome/shelly/script.UploadWithVersionAndStart instead

Types

type Configuration

type Configuration struct {
	Id     uint32 `json:"id"`               // Id of the script
	Name   string `json:"name,omitempty"`   // Name of the script
	Enable bool   `json:"enable,omitempty"` // true if the script runs by default on boot, false otherwise
}

type ConfigurationRequest

type ConfigurationRequest struct {
	Id            uint32        `json:"id"`     // Id of the script
	Configuration Configuration `json:"config"` // Configuration of the script
}

type DeviceState

type DeviceState struct {
	KVS     map[string]interface{} `json:"kvs"`
	Storage map[string]interface{} `json:"storage"`

	// Schedules tracks jobs created via Schedule.Create during script execution.
	// Each entry is the raw params map passed to Schedule.Create, plus an "id" field.
	Schedules []map[string]interface{} `json:"schedules,omitempty"`

	// ComponentStatus controls what Shelly.getComponentStatus() returns for
	// each component key (e.g. "switch:0", "input:1", "sys", "mqtt").
	// Populated by tests or loaded from a device snapshot (see FetchDeviceState).
	ComponentStatus map[string]interface{} `json:"component_status,omitempty"`

	// EventInjector, when non-nil, allows a test to push raw JSON-encoded
	// device-event objects into the running script's event-handler loop.
	// Send a JSON object with the same shape as Shelly device events:
	//   {"info": {"event": "pool-pump/night-stop"}}
	EventInjector chan []byte `json:"-"`

	// OnModified is called whenever the device state is modified (KVS.Set, config changes, etc.)
	// This allows automatic persistence of state changes during script execution
	OnModified func() `json:"-"`
	// contains filtered or unexported fields
}

DeviceState represents the persistent state of a Shelly device for testing

func FetchDeviceState

func FetchDeviceState(ctx context.Context, via types.Channel, device types.Device) (*DeviceState, error)

FetchDeviceState fetches the live state of a Shelly device and returns a DeviceState suitable for use with RunWithDeviceState or SaveDeviceState.

Fetched fields:

  • KVS: all key-value pairs stored on the device
  • ComponentStatus: point-in-time snapshot of all component statuses
  • Storage: always empty (Script.storage is not accessible via RPC)

func LoadDeviceState

func LoadDeviceState(log logr.Logger, filename string) (*DeviceState, error)

LoadDeviceState loads device state from a JSON file If the file doesn't exist, returns an empty state

func (*DeviceState) AddSchedule

func (d *DeviceState) AddSchedule(job map[string]interface{}) int

AddSchedule appends a schedule and returns its assigned ID (1-based).

func (*DeviceState) DeleteSchedule

func (d *DeviceState) DeleteSchedule(id int)

DeleteSchedule removes the schedule with the given ID.

func (*DeviceState) GetKVS

func (d *DeviceState) GetKVS() map[string]interface{}

GetKVS implements the DeviceState interface

func (*DeviceState) GetStorage

func (d *DeviceState) GetStorage() map[string]interface{}

GetStorage implements the DeviceState interface

type EvalRequest

type EvalRequest struct {
	Id   uint32 `json:"id"`   // Id of the script
	Code string `json:"code"` // Argument to evaluate (the length must be greater than 0). Required
}

type EvalResponse

type EvalResponse struct {
	Result string `json:"result"` // The result of the evaluation
}

type FormerStatus

type FormerStatus struct {
	WasRunning bool `json:"was_running"` // true if the script was running before the operation, false otherwise
}

type GetCodeRequest

type GetCodeRequest struct {
	Id     uint32 `json:"id"`               // Id of the script
	Offset uint32 `json:"offset,omitempty"` // Byte offset from the beginning. Default value: 0. Optional
	Length uint32 `json:"len,omitempty"`    // Bytes to read. Default value: maximum possible number of bytes till the end is reached. Optional
}

type GetCodeResponse

type GetCodeResponse struct {
	Data string `json:"data"` // The requested data chunk
	Left uint32 `json:"left"` // Number of bytes remaining till the end of the code
}

type ListResponse

type ListResponse struct {
	Scripts []Status `json:"scripts"` // List of scripts
}

type PutCodeRequest

type PutCodeRequest struct {
	Id     uint32 `json:"id"`               // Id of the script
	Code   string `json:"code"`             // The code which will be included in the script (the length must be greater than 0). Required
	Append bool   `json:"append,omitempty"` // true to append the code, false otherwise. If set to false, the existing code will be overwritten. Default value: false. Optional
}

type PutCodeResponse

type PutCodeResponse struct {
	Length uint `json:"len"` // The total code length in bytes
}

type Status

type Status struct {
	Id           uint32   `json:"id"`                  // Id of the script
	Running      bool     `json:"running"`             // true if the script is currently running, false otherwise (absent at configuration-time)
	Name         string   `json:"name,omitempty"`      // Name of the script
	MemUsed      uint32   `json:"mem_used,omitempty"`  // Memory used by the script in bytes
	MemPeak      uint32   `json:"mem_peak,omitempty"`  // Peak memory used by the script in bytes
	MemFree      uint32   `json:"mem_free,omitempty"`  // Free memory available to the script in bytes
	Manual       bool     `json:"loaded,omitempty"`    // Is loaded on the device
	Errors       []string `json:"errors,omitempty"`    // Optional, present only when the script execution resulted in an error. The array contains description of the type of error.
	ErrorMessage string   `json:"error_msg,omitempty"` // Optional, present only when the script execution resulted in an error. The array contains error message (stack trace).
}

func DeviceStatus

func DeviceStatus(ctx context.Context, device types.Device, via types.Channel) ([]Status, error)

func ListLoaded

func ListLoaded(ctx context.Context, via types.Channel, device types.Device) ([]Status, error)

func ScriptStatus

func ScriptStatus(ctx context.Context, device types.Device, via types.Channel, name string) (*Status, error)

type StatusStartStopDeleteRequest

type StatusStartStopDeleteRequest struct {
	Id uint32 `json:"id"` // Id of the script
}

type Verb

type Verb string
const (
	SetConfig Verb = "Script.SetConfig"
	GetConfig Verb = "Script.GetConfig"
	GetStatus Verb = "Script.GetStatus"
	List      Verb = "Script.List"
	Create    Verb = "Script.Create"
	Start     Verb = "Script.Start"
	Delete    Verb = "Script.Delete"
	Stop      Verb = "Script.Stop"
	PutCode   Verb = "Script.PutCode"
	GetCode   Verb = "Script.GetCode"
	Eval      Verb = "Script.Eval"
)

func (Verb) String

func (v Verb) String() string

Jump to

Keyboard shortcuts

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