devicecommand

package
v0.47.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 36 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package devicecommand is the task type "device_command" (TASK-01 to TASK-12): it resolves device, service and protocol, marshals the command, sends it to the protocol handler and completes the task with the unmarshalled answer, for single devices and device groups.

Index

Constants

View Source
const (
	Optimistic  = "optimistic"
	Pessimistic = "pessimistic"

	Parallel   = "parallel"
	Sequential = "sequential"
	RoundRobin = "round_robin"
)
View Source
const (
	LocalResponseTopic = "response/#"
	LocalErrorTopic    = "error/command/#"
)
View Source
const TaskType = "device_command"

Variables

This section is empty.

Functions

This section is empty.

Types

type AdditionalFunction added in v0.46.0

type AdditionalFunction struct {
	Name             string              `json:"name"`
	Function         models.Function     `json:"function"`
	CharacteristicId string              `json:"characteristic_id"`
	Aspects          []models.AspectNode `json:"aspects,omitempty"`
	Input            any                 `json:"input,omitempty"`
}

AdditionalFunction is a controlling function that a device command sends in the same message as its primary function (SNRGY-5157). Its value is the input entry of the same name.

type Command

type Command struct {
	Version int64 `json:"version"`

	// modeling time
	Function         models.Function `json:"function"`
	CharacteristicId string          `json:"characteristic_id"`
	// version >= 3, controlling functions only, sent in the same message as Function
	AdditionalFunctions []AdditionalFunction `json:"additional_functions,omitempty"`

	// optional modeling time, limits the device and service selection in the deployment
	DeviceClass *models.DeviceClass `json:"device_class,omitempty"`
	// Deprecated: use Aspects
	Aspect  *models.AspectNode  `json:"aspect,omitempty"`
	Aspects []models.AspectNode `json:"aspects,omitempty"`

	// deployment time
	DeviceGroupId string           `json:"device_group_id"`
	DeviceId      string           `json:"device_id,omitempty"`
	Device        *models.Device   `json:"device,omitempty"`
	ServiceId     string           `json:"service_id,omitempty"`
	Service       *models.Service  `json:"service,omitempty"`
	Protocol      *models.Protocol `json:"protocol,omitempty"`
	ProtocolId    string           `json:"protocol_id,omitempty"`

	// version <= 2
	Configurables        []Configurable `json:"configurables,omitempty"`
	ContentVariableHints []string       `json:"content_variable_hints,omitempty"`

	// version >= 3
	InputPaths      []string         `json:"input_paths,omitempty"`
	OutputPath      string           `json:"output_path,omitempty"`
	ConfigurablesV2 []ConfigurableV2 `json:"configurables_v2,omitempty"`

	PreferEvent bool `json:"prefer_event"`

	// runtime
	Input  any `json:"input,omitempty"`
	Output any `json:"output,omitempty"`

	Retries int64 `json:"retries,omitempty"`
}

func (Command) GetAspects

func (this Command) GetAspects() []models.AspectNode

GetAspects returns the aspects the command asks for; a service has to serve all of them.

func (*Command) SetAspects

func (this *Command) SetAspects()

SetAspects folds the deprecated Aspect into Aspects.

type Completer

type Completer interface {
	CompleteTask(ctx context.Context, jobId string, output map[string]any) (bool, error)
	FailTask(ctx context.Context, jobId string, message string) (bool, error)
	FailTaskError(ctx context.Context, jobId string, taskErr error) (bool, error)
}

Completer delivers asynchronous answers to the engine.

type Config

type Config struct {
	// parallel, sequential or round_robin for device groups (TASK-06)
	GroupScheduler string
	// sequential and round_robin: sub-tasks with an open try at the same time, unless the
	// element sets senergy:groupConcurrency (SNRGY-5093); default 1
	GroupConcurrency int
	// echoed in the metadata of each message; the handlers answer there (TASK-05)
	ResponseTo       string
	ErrorTo          string
	TimescaleTimeout time.Duration
	// on a gateway: the prefix of the command ids on its broker, which tells answers to this
	// engine apart from those to device-command and the cloud (FOG-01)
	LocalCommandPrefix string
	// how long reads of device-repository are cached, per user (device_cache_timeout)
	DeviceCacheTimeout time.Duration
}

type Configurable

type Configurable = configurables.Configurable

type ConfigurableV2

type ConfigurableV2 struct {
	Path             string              `json:"path"`
	CharacteristicId string              `json:"characteristic_id"`
	AspectNode       models.AspectNode   `json:"aspect_node"` // Deprecated: use AspectNodes
	AspectNodes      []models.AspectNode `json:"aspect_nodes,omitempty"`
	FunctionId       string              `json:"function_id"`
	Value            any                 `json:"value,omitempty"`
	Type             string              `json:"type,omitempty"`
}

ConfigurableV2 is the configurable as process-deployment writes it into the task payload; it mirrors the configurable of a device-repository path option.

func (ConfigurableV2) GetAspectNodes

func (this ConfigurableV2) GetAspectNodes() []models.AspectNode

GetAspectNodes returns the aspect nodes; the deprecated AspectNode is a list with one element.

type EventRequest

type EventRequest struct {
	Device           models.Device
	Service          models.Service
	Protocol         models.Protocol
	CharacteristicId string
	FunctionId       string
	AspectNodes      []models.AspectNode
}

EventRequest reads the last value of an event service instead of sending a request

type LastValues

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

LastValues reads the last values of event services from mgw-last-value on a gateway, by local ids; the column is the path below the root content variable. A value never received is an error, as mgw-external-task-worker treats it.

func NewLastValues

func NewLastValues(url string) *LastValues

func (*LastValues) Query

func (this *LastValues) Query(token string, request []TimescaleRequest, timeout time.Duration) ([]TimescaleResponse, error)

type LocalEnvelope

type LocalEnvelope struct {
	CommandId string `json:"command_id"`
	Data      string `json:"data"`
}

LocalEnvelope is a command to a device connector on the broker of a gateway, and its answer.

type LocalTransport

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

LocalTransport sends protocol messages to the device connectors of a gateway.

func NewLocalTransport

func NewLocalTransport(broker mqtt.Broker, prefix string) *LocalTransport

func (*LocalTransport) Produce

func (this *LocalTransport) Produce(ctx context.Context, _ string, _ string, payload []byte) error

Produce publishes the data segment of a protocol message; the task id becomes the command id

type Marshaller

type Marshaller interface {
	Marshal(ctx context.Context, request MarshallingRequest) (result map[string]string, err error, code int)
	Unmarshal(ctx context.Context, request UnmarshallingRequest) (result interface{}, err error, code int)
	MarshalV2(ctx context.Context, request MarshallingV2Request) (result map[string]string, err error, code int)
	UnmarshalV2(ctx context.Context, request UnmarshallingV2Request) (result interface{}, err error, code int)
}

Marshaller is the part of the marshaller service the device commands use, in the signatures of its client (marshaller/lib/client), which implements it; on gateways NewLocalMarshaller does. Commands of payload version 3 use the V2 methods. The code is the http status of the answer.

func NewLocalMarshaller

func NewLocalMarshaller(ctx context.Context, repository devicerepository.Interface, cacheDuration time.Duration, refresh time.Duration, logger *slog.Logger) (Marshaller, error)

NewLocalMarshaller marshals with the device-repository mirror behind repository; the concepts of marshaller v1 are loaded on first use and refreshed at the interval.

type MarshallingRequest added in v0.24.0

type MarshallingRequest = messages.MarshallingRequest

type MarshallingV2Request added in v0.24.0

type MarshallingV2Request = messages.MarshallingV2Request

type Metadata

type Metadata struct {
	Version  int64           `json:"version,omitempty"`
	Device   models.Device   `json:"device"`
	Service  models.Service  `json:"service"`
	Protocol models.Protocol `json:"protocol"`
	// only for version >= 3
	OutputPath string `json:"output_path,omitempty"`
	// only for version >= 3 if no OutputPath is known
	OutputFunctionId string `json:"output_function_id,omitempty"`
	// Deprecated: use OutputAspectNodes
	OutputAspectNode *models.AspectNode `json:"output_aspect_node,omitempty"`
	// only for version >= 3 if no OutputPath is known
	OutputAspectNodes    []models.AspectNode `json:"output_aspect_nodes,omitempty"`
	InputCharacteristic  string              `json:"input_characteristic,omitempty"`
	OutputCharacteristic string              `json:"output_characteristic,omitempty"`
	// only for version < 3
	ContentVariableHints []string `json:"content_variable_hints,omitempty"`
	ResponseTo           string   `json:"response_to"`
	ErrorTo              string   `json:"error_to,omitempty"`
}

func (Metadata) GetOutputAspectNodes

func (this Metadata) GetOutputAspectNodes() []models.AspectNode

GetOutputAspectNodes returns the aspects of the expected response.

func (*Metadata) SetOutputAspectNodes

func (this *Metadata) SetOutputAspectNodes(aspectNodes []models.AspectNode)

SetOutputAspectNodes sets the aspects of the expected response and the deprecated single node: the one with the alphabetically first id, as device-repository fills it.

type Metrics

type Metrics interface {
	CommandSent(userId string, deploymentId string)
	MarshallingLatency(endpoint string, userId string, serviceId string, functionIds string, duration time.Duration)
}

Metrics keep the names and labels the cost-calculator reads (TASK-12).

type Overwrite

type Overwrite struct {
	DeviceId   string           `json:"device_id,omitempty"`
	Device     *models.Device   `json:"device,omitempty"`
	ServiceId  string           `json:"service_id,omitempty"`
	Service    *models.Service  `json:"service,omitempty"`
	Protocol   *models.Protocol `json:"protocol,omitempty"`
	ProtocolId string           `json:"protocol_id,omitempty"`
}

type Producer

type Producer interface {
	Produce(ctx context.Context, topic string, key string, payload []byte) error
}

Producer sends a message to a topic; a topic that is an http(s) URL gets a POST (TASK-04).

type ProtocolMsg

type ProtocolMsg struct {
	Request  ProtocolRequest  `json:"request"`
	Response ProtocolResponse `json:"response"`
	TaskInfo TaskInfo         `json:"task_info"`
	Metadata Metadata         `json:"metadata"`
	Trace    []Trace          `json:"trace,omitempty"`
}

type ProtocolRequest

type ProtocolRequest struct {
	Input map[string]string `json:"input"`
}

type ProtocolResponse

type ProtocolResponse struct {
	Output map[string]string `json:"output"`
}

type TaskInfo

type TaskInfo struct {
	WorkerId          string `json:"worker_id"`
	TaskId            string `json:"task_id"`
	ProcessInstanceId string `json:"process_instance_id"`
	// the deployment of the instance (DATA-04)
	DeploymentId string `json:"deployment_id"`
	// Deprecated: the old name of DeploymentId, filled with the same id until every connector
	// mirrors deployment_id with platform-connector-lib (DATA-04)
	ProcessDefinitionId string `json:"process_definition_id"`
	CompletionStrategy  string `json:"completion_strategy"`
	Time                string `json:"time"`
	TenantId            string `json:"tenant_id"`
	BusinessKey         string `json:"business_key"`
}

type Timescale

type Timescale interface {
	Query(token string, request []TimescaleRequest, timeout time.Duration) ([]TimescaleResponse, error)
}

Timescale reads the last values of event services from timescale-wrapper.

func NewTimescale

func NewTimescale(url string) Timescale

type TimescaleRequest

type TimescaleRequest struct {
	Device     models.Device
	Service    models.Service
	ColumnName string
}

type TimescaleResponse

type TimescaleResponse struct {
	Time  *string `json:"time"`
	Value any     `json:"value"`
}

type Trace

type Trace struct {
	TimeUnit  string `json:"time_unit"`
	Timestamp int64  `json:"timestamp"`
	Location  string `json:"location"`
}

type Transport

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

Transport sends commands to Kafka topics or, for protocol handlers given as URL, by HTTP; LocalTransport is its counterpart on a gateway.

func NewTransport

func NewTransport(ctx context.Context, kafkaUrl string) *Transport

NewTransport creates a transport; without kafkaUrl only HTTP handlers can be reached.

func (*Transport) Produce

func (this *Transport) Produce(ctx context.Context, topic string, key string, payload []byte) error

type Type

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

func New

func New(config Config, s *store.Store, iot devicerepository.Interface, tokens auth.UserTokenSource, m Marshaller, ts Timescale, producer Producer, metrics Metrics, logger *slog.Logger) *Type

func (*Type) Config added in v0.33.1

func (this *Type) Config() Config

Config is the configuration in effect, with the defaults of New

func (*Type) Defaults

func (this *Type) Defaults(input map[string]any) (*int, *time.Duration)

Defaults takes the retries of the payload, as the external-task-worker did (TASK-07). The sequential and round robin schedulers count the retries of the task per sub-task (TASK-06): a try waits for the answer of one device, so the task timeout is the answer timeout of each try, and a group takes up to sub-tasks × (retries + 1) timeouts, divided by the concurrency (see OnTimeout).

func (*Type) Execute

func (this *Type) Execute(ctx context.Context, task engine.Task) (engine.TaskResult, error)

func (*Type) FailureVariables added in v0.38.0

func (this *Type) FailureVariables(tx *store.Tx, job store.Job) (map[string]any, error)

FailureVariables names the device and service of a failed device command whose failure carries none, e.g. after a timeout: those of its only sub-task, or of the only one without result. A group with several devices without an answer names none (BPMN-19).

func (*Type) HandleError

func (this *Type) HandleError(ctx context.Context, raw []byte) error

HandleError processes an error of a protocol handler; the task is retried or becomes an incident.

func (*Type) HandleLocalError

func (this *Type) HandleLocalError(ctx context.Context, topic string, payload []byte) error

HandleLocalError fails the task of a command the connector could not deliver.

func (*Type) HandleLocalResponse

func (this *Type) HandleLocalResponse(ctx context.Context, _ string, payload []byte) error

HandleLocalResponse completes the sub-task of an answer of a device connector. The protocol message is formed again from the stored sub-task, so that a restart loses no correlation.

func (*Type) HandleResponse

func (this *Type) HandleResponse(ctx context.Context, raw []byte) error

HandleResponse processes an answer of a protocol handler from Kafka or HTTP (TASK-05). An answer for an unknown or finished task is dropped, so that every task completes at most once.

func (*Type) OnTimeout

func (this *Type) OnTimeout(ctx context.Context, tx *store.Tx, task engine.Task) (*engine.TaskResult, error)

OnTimeout handles the timeout of a task with several sub-tasks (TASK-06). One at a time, the task timeout is the answer timeout of each try and does not count as failed attempt: while open tries take every place, or nothing else is left to send, the task waits until the first of their windows ends, so that a command sent after the task was locked, e.g. on the answer of the previous device, gets its full timeout; otherwise the task is executed again and asks the next device or ends with the answers it has. In parallel, the last attempt completes with the results it has; without any result the timeout is a failure.

func (*Type) SetCompleter

func (this *Type) SetCompleter(c Completer)

SetCompleter connects the type with the engine, which is created after it. The type takes the clock of the engine, since the tries of sub-tasks are compared with its timeouts, and its processes for the attributes of elements.

type UnmarshallingRequest added in v0.24.0

type UnmarshallingRequest = messages.UnmarshallingRequest

type UnmarshallingV2Request

type UnmarshallingV2Request = messages.UnmarshallingV2Request

Jump to

Keyboard shortcuts

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