acapapp

package
v1.5.4 Latest Latest
Warning

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

Go to latest
Published: May 3, 2024 License: GPL-3.0 Imports: 22 Imported by: 0

Documentation

Overview

Package acapapp provides a high-level abstraction for an Axis Communications Application Platform (ACAP) application. It encapsulates the application's manifest, system logging, parameter handling, event handling, and the main event loop to facilitate easy development of ACAP applications. This includes automatic loading of the application's manifest, initialization of syslog for logging, handling of application parameters, event handling, and the GMainLoop for the main event loop.

Index

Constants

View Source
const (
	// FrameProviderStateError indicates an error state where the frame provider cannot recover without intervention.
	FrameProviderStateError FrameProviderState = iota
	// FrameProviderStateStopped indicates the frame provider is stopped and not currently providing frames.
	FrameProviderStateStopped
	// FrameProviderStateStarted indicates the frame provider is actively providing frames.
	FrameProviderStateStarted
	// FrameProviderStateRestarting indicates the frame provider is in the process of restarting.
	FrameProviderStateRestarting
	// FrameProviderStateInit indicates the frame provider is initialized but not yet started.
	FrameProviderStateInit
	// MaxRestartRetries defines the maximum number of restart attempts for the frame provider before entering an error state.
	MaxRestartRetries int = 4
)

Variables

This section is empty.

Functions

func NewCameraApplicationPlatformEvent

func NewCameraApplicationPlatformEvent(app_setup axmanifest.Setup, event_name string, event_nice_name *string, event_entries []*EventEntry) (*axevent.AXEventKeyValueSet, error)

NewCameraApplicationPlatformEvent creates a new AXEventKeyValueSet instance for representing a Camera Application Platform event. This function encapsulates the process of initializing an event with specific application setup details, event identifiers, key-value pairs for event data, and various types of markers (source, data, user-defined) to provide additional context or categorization for the event data. Additionally, it facilitates assigning 'nice names' to event key-value pairs for enhanced readability.

Parameters:

  • app_setup: An axmanifest.Setup structure containing the application setup details. It includes information such as application name and friendly name, which are used to contextualize the event within a specific application platform.
  • event_name: A string representing the unique identifier of the event.
  • event_nice_name: An optional pointer to a string that provides a human-readable name for the event. If provided, it overrides the default event name in the context where 'nice names' are used.
  • event_entries: A slice of pointers to EventEntry structures, each representing a key-value pair with additional metadata

Returns:

  • A pointer to an AXEventKeyValueSet instance.
  • An error, which will be non-nil if any part of the event creation process fails.

The function utilizes the NewTnsAxisEvent helper function to initialize the AXEventKeyValueSet, specifying a structured set of topics ('topic0' to 'topic3'). Specifically, the topics are assigned as follows:

  • 'topic0' is set to "CameraApplicationPlatform", identifying the event as part of the Camera Application Platform. This serves as the primary categorization layer, indicating the event's general domain.
  • 'topic1' is derived from the `app_setup.AppName`, tying the event to a specific application by its name. This further refines the event's context within the platform, associating it with a particular application's events.
  • 'topic2' is optionally set to a user-provided string via `event_name` or `event_nice_name`, if provided. This allows for a more descriptive labeling of the event, enhancing the readability and interpretability of the event data. If `event_nice_name` is not null, it prefixes the nice name with the app's friendly name for clearer identification. If both are null, `topic2` effectively utilizes the raw `event_name` for technical identification.
  • 'topic3' is intentionally left as nil/null.

func SignalHandler

func SignalHandler(handler func())

func UnmarshalEvent

func UnmarshalEvent(e *axevent.Event, v interface{}) error

UnmarshalEvent unmarshals the given event into the provided struct.

Types

type AcapApplication

type AcapApplication struct {
	Manifest        *axmanifest.ApplicationManifestSchema
	Syslog          *axsyslog.Syslog
	ParamHandler    *axparameter.AXParameter
	EventHandler    *axevent.AXEventHandler
	FrameProvider   *FrameProvider
	StorageProvider *StorageProvider
	Mainloop        *glib.GMainLoop
	OnCloseCleaners []func()

	Larod *axlarod.Larod
	// contains filtered or unexported fields
}

AcapApplication provides a high-level abstraction for an Axis Communications Application Platform (ACAP) application. It encapsulates the application's manifest, system logging, parameter handling, event handling, and the main event loop to facilitate easy development of ACAP applications. This includes automatic loading of the application's manifest, initialization of syslog for logging, handling of application parameters, event handling, and the GMainLoop for the main event loop.

func NewAcapApplication

func NewAcapApplication() *AcapApplication

NewAcapApplication initializes a new AcapApplication instance, loading the application's manifest, setting up the syslog, parameter handler, event handler, and main loop. It returns an initialized AcapApplication instance.

! Note: Since this is the entry point, it panic in case of an error, this could happen if manifest could not loaded or parameter instance could not be created

func (*AcapApplication) AcapWebBaseUri

func (a *AcapApplication) AcapWebBaseUri() (string, error)

AcapWebBaseUri returns the base path for an webserver that is used with reverse proxy reverse proxy uri for acap are: /local/<appname>/<apipath>

func (*AcapApplication) AddCameraPlatformEvent

func (a *AcapApplication) AddCameraPlatformEvent(cpe *CameraPlatformEvent) (int, error)

AddCameraPlatformEvent adds the event to the application. AcapApplication undaclare the added events on closing or exit signals.

func (*AcapApplication) AddCloseCleanFunc

func (a *AcapApplication) AddCloseCleanFunc(f func())

Add close or clean functions to app so in case of signals these are correct handled

func (*AcapApplication) AddModelCleaner

func (a *AcapApplication) AddModelCleaner(m *axlarod.LarodModel)

func (*AcapApplication) Close

func (a *AcapApplication) Close()

Close terminates the application's main event loop and releases resources associated with the syslog, parameter handler, event handler, and main loop. This should be called to cleanly shut down the application.

func (*AcapApplication) GetSnapshot

func (a *AcapApplication) GetSnapshot(video_channel int) ([]byte, error)

GetSnapshot captures a JPEG snapshot from the specified video channel and returns it as a byte slice. It sets up the required settings for capturing the snapshot, captures it, and then returns the snapshot data or an error if the capture fails.

func (*AcapApplication) InitalizeLarod

func (a *AcapApplication) InitalizeLarod() error

func (*AcapApplication) IsLicenseValid

func (a *AcapApplication) IsLicenseValid(major_version int, minor_version int) (bool, error)

IsLicenseValid checks the validity of the application's license for a given major and minor version. It returns true if the license is valid, or false along with an error if the check fails.

func (*AcapApplication) NewFrameProvider

func (a *AcapApplication) NewFrameProvider(config axvdo.VideoSteamConfiguration) error

NewFrameProvider initializes a new FrameProvider with the given configuration and application context. It prepares the frame provider for operation but does not start streaming frames until Start is called.

Note:

Currently this supports only one FrameProvider per application. If you need more then one dont use frameProvider in AcapApplication.
Create a new FrameProvider for each stream, and manage them separately, dont forget to call Stop() when you are done.

func (*AcapApplication) NewStorageProvider

func (a *AcapApplication) NewStorageProvider(useChannelEvents bool)

NewStorageProvider initializes and returns a new StorageProvider associated with a given AcapApplication. Whem useChannelEvents is true the DiskItemsEvents channel got events from subscriptions callbacks in form of *axstorage.DiskItem. Its an unbufferd channel with cap 10

func (*AcapApplication) OnEvent

func (a *AcapApplication) OnEvent(kvs *axevent.AXEventKeyValueSet, callback func(*axevent.Event)) (subscription int, err error)

OnEvent creates a subscription callback for the given event key value set.

func (*AcapApplication) Run

func (a *AcapApplication) Run()

Start initiates the main event loop of the application, beginning its execution.

func (*AcapApplication) RunInBackground

func (a *AcapApplication) RunInBackground()

func (*AcapApplication) SendPlatformEvent

func (a *AcapApplication) SendPlatformEvent(eventID int, createEventFunc func() (*axevent.AXEvent, error)) error

SendPlatformEvent sends a platform event with the specified event ID and event creation function.

type CameraPlatformEvent

type CameraPlatformEvent struct {
	// Name is a unique identifier for the event.
	Name string
	// NiceName is an optional human-readable name for the event.
	NiceName *string
	// KeyValueExtendedEntries is a slice of EventEntry structures, each representing a key-value pair with additional metadata.
	Entries []*EventEntry
	// Stateless indicates whether the event is stateless or not.
	// A stateless event, as defined in the AXEvent library, does not maintain any persistent state
	// and exists only at the moment it is sent. Such events are akin to signals or pulses, representing
	// instantaneous occurrences without an ongoing state. Examples of stateless events include momentary
	// interactions or occurrences, such as "a point crossed a line".
	//
	// In the context of event declarations, stateless events require the specification of all constituent
	// keys within the event. For keys with fixed values, these values must be explicitly provided. Conversely,
	// for keys that can assume variable values, their values should be set to nil in the declaration to
	// indicate their dynamic nature. This distinction is crucial for ensuring the correct interpretation
	// and handling of the event data.
	//
	// Setting this field to true characterizes the event as stateless, implying that it is transient and
	// does not relate to any persistent state. This is contrasted with stateful events, where the event's
	// state persists over time and may represent ongoing conditions or statuses, such as the active or
	// inactive state of an I/O port. In the declaration of stateful events, all keys must also be specified,
	// with variable values initialized to their starting state.
	Stateless bool
}

CameraPlatformEvent represents an event declaration for the Camera Application Platform.

func (*CameraPlatformEvent) NewEvent

func (cpe *CameraPlatformEvent) NewEvent(valuesMap KeyValueMap) (*axevent.AXEvent, error)

NewEvent creates a new AXEvent based on predefined keys and dynamic values. It returns the new AXEvent or an error if the values provided do not match the expected types. The valuesMap parameter should contain the values for each key in the KeyValueSet. The keys in the valuesMap should match the keys in the KeyValueSet of the CameraPlatformEvent.

type EventEntry

type EventEntry struct {
	// Key: The key for the underlaying ax_event_key_value_set
	Key string
	// Namespace: The namespace of the key or nil.
	Namespace *string
	// Value: The data associated with the key. This can be any type of data relevant to the event.
	Value interface{}
	// IsSource: An optional flag that, when set, marks the key as a source. Sources are identifiers
	// used to distinguish between multiple instances of the same event declaration. For example, if a device
	// has multiple I/O ports, the key representing which port the event is for could be marked as a source.
	// It's important to note that while multiple keys can be marked as source, only events with zero or one
	// source keys are eligible for triggering actions.
	IsSource *bool
	// IsData: An optional flag that, when set, marks the key as data. Data keys represent the state or value
	// of what the event is about, such as the high or low state of an I/O port. Similar to IsSource, although
	// it's possible to mark more than one key as data, only events with exactly one data key can be used to
	// trigger actions.
	IsData *bool
	// UserDefined: An optional field that allows users to attach a custom tag to the key-value pair. This tag
	// can be used for additional identification or categorization beyond what is provided by the key and namespace.
	UserDefined *string
	// KeyNiceName: An optional, human-readable name for the key. This is useful for providing clear, understandable
	// labels for keys when displayed to end-users, enhancing the usability and accessibility of event data.
	KeyNiceName *string
	// ValueNiceName: Similar to KeyNiceName, this is an optional, human-readable name for the value. It serves
	// the same purpose of enhancing clarity and understanding for end-users.
	ValueNiceName *string
	// ValueType: Specifies the type of the value, using the AXEventValueType enumeration. This helps ensure
	// consistent interpretation and handling of the value data across different parts of the system.
	ValueType axevent.AXEventValueType
}

EventEntry represents a extended version of an key value pair for a ax_event_key_value_set with additional metadata.

type FrameProvider

type FrameProvider struct {
	Config axvdo.VideoSteamConfiguration // Configuration for the video stream.

	FrameStreamChannel chan *axvdo.VideoFrame // Channel for delivering video frames to consumers.

	PostProcessModel *axlarod.LarodModel // Post proccessor for the frame provider, combination of the pp model and the frame provider
	// contains filtered or unexported fields
}

FrameProvider encapsulates the management of video frame streaming, including starting, stopping, and restarting the stream.

func (*FrameProvider) IsRunning

func (fp *FrameProvider) IsRunning() bool

IsRunning checks if the FrameProvider is currently active and streaming frames.

func (*FrameProvider) Restart

func (fp *FrameProvider) Restart() error

Restart attempts to restart the video stream, first stopping the current stream and then re-initializing and starting a new stream. It applies a delay before attempting the restart to give the system time to release resources.

func (*FrameProvider) SetLarodPostProccessor added in v1.0.2

func (fp *FrameProvider) SetLarodPostProccessor(device string, rgbMode axlarod.PreProccessOutputFormat, outReso *axvdo.VdoResolution, frameProccessor func([]byte) []byte) error

SetLarodPostProccessor initializes the post processor for the frame provider. It creates a new preprocessor model based on the given device, output resolution, and RGB mode. The post processor is used to convert the raw video frame data into a format suitable for processing by the detection model.

func (*FrameProvider) Start

func (fp *FrameProvider) Start() error

Start begins the frame streaming process, marking the FrameProvider as running and initiating the frame fetching loop. If an error occurs while starting the stream, it returns the error without altering the provider's state. Handles automatic restart in case of an expected Vdo error

func (*FrameProvider) State

func (fp *FrameProvider) State() FrameProviderState

State returns the current state of the FrameProvider, providing insight into whether it's running, stopped, or in an error state.

func (*FrameProvider) Stats

func (fp *FrameProvider) Stats() (*FrameProviderStats, error)

Stats gathers and returns statistical information about the frame provider's operation, including internal buffer lengths and stream statistics.

func (*FrameProvider) Stop

func (fp *FrameProvider) Stop()

Stop halts the frame streaming process, changing the state of the FrameProvider to stopped and cleaning up resources.

type FrameProviderState

type FrameProviderState int

FrameProviderState defines the possible states of a FrameProvider.

type FrameProviderStats

type FrameProviderStats struct {
	InternalChannelBufferLen int               // The current length of the frame stream channel buffer.
	RestartRetries           int               // The number of restart attempts made since the last successful start.
	StreamStats              axvdo.StreamStats // Statistics gathered from the video stream.
}

FrameProviderStats provides statistical information about the operation of a FrameProvider.

type KeyValueMap

type KeyValueMap map[string]interface{}

type Overlay

type Overlay struct {
	OverlayData      *axoverlay.AxOverlayOverlayData
	Camera           int
	UseMaxResolution bool
	Userdata         any
	// contains filtered or unexported fields
}

func NewAnchorCenterRrgbaOverlay

func NewAnchorCenterRrgbaOverlay(positonType axoverlay.AxOverlayPositionType, userData any) *Overlay

Creates a default overlay with anchor center and ARGB32 colorspace

func (*Overlay) Destroy

func (ov *Overlay) Destroy()

func (*Overlay) SetMaxResolution

func (ov *Overlay) SetMaxResolution(camera int) (err error)

type OverlayProvider

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

func NewOverlayProvider

func NewOverlayProvider(renderCallback axoverlay.AxOverlayRenderCallback, adjustmentCallback axoverlay.AxOverlayAdjustmentCallback, streamSelectCallback axoverlay.AxOverlayStreamSelectCallback) (*OverlayProvider, error)

Creates a cairo backend overlay Provider, this can only created once !!!

func (*OverlayProvider) AddOverlay

func (op *OverlayProvider) AddOverlay(overlay *Overlay) (overlayId int, err error)

func (*OverlayProvider) Cleanup

func (op *OverlayProvider) Cleanup()

func (*OverlayProvider) Redraw

func (op *OverlayProvider) Redraw() error

func (*OverlayProvider) RemoveOverlay

func (op *OverlayProvider) RemoveOverlay(overlayId int) error

type RwError

type RwError int

RwError represents various errors that can occur during read/write operations on storage devices.

const (
	RWErrorNone RwError = iota
	RWErrorFull
	RWErrorNotAvalible
	RWErrorNotSetuped
	RWErrorNotWriteable
	RWErrorNotUpdateable
	RWErrorOs
)

type RwResult

type RwResult struct {
	RwError RwError // Specific write error encountered, if any.
	Error   error   // General error encountered during the operation.
	Data    []byte  // Data read from storage, applicable for read operations.
}

RwResult encapsulates the result of a read/write operation, including any errors that occurred.

type StorageProvider

type StorageProvider struct {
	DiskItems []*axstorage.DiskItem // List of disk items representing storage devices.

	DiskItemsEvents  chan *axstorage.DiskItem
	UseChannelEvents bool
	// contains filtered or unexported fields
}

StorageProvider represents a handler for managing storage devices, enabling operations such as file writing, removal, and subscriptions to storage events.

func (*StorageProvider) Close

func (sp *StorageProvider) Close()

Close unsubscribes and release all storages/disks

func (*StorageProvider) GetDiskItem

func (sp *StorageProvider) GetDiskItem(storageId axstorage.StorageId) (*axstorage.DiskItem, bool)

GetDiskItem searches for a DiskItem by its storageId among the managed storage devices. It returns the found DiskItem and a boolean indicating whether the search was successful.

func (*StorageProvider) GetDiskItemById

func (sp *StorageProvider) GetDiskItemById(storageId string) (sdCardDiskItem *axstorage.DiskItem, found bool)

Get DiskItem with storage id SD_DISK

func (*StorageProvider) Open

func (sp *StorageProvider) Open() error

Open searches for storage devices, creates callbacks for event subscriptions, and manages them. This method attempts to establish communication with all available storages and subscribes to their respective events for monitoring changes in their state or attributes.

func (*StorageProvider) ReadFile

func (sp *StorageProvider) ReadFile(di *axstorage.DiskItem, filePath string) *RwResult

ReadFile reads the content of a specified file from the disk item. It returns an RwResult containing the read data and any errors that occurred.

func (*StorageProvider) Release

func (sp *StorageProvider) Release(diskItem *axstorage.DiskItem) error

Release async release a disk/storage

func (*StorageProvider) ReleaseAll

func (sp *StorageProvider) ReleaseAll()

UnsubscribeAll Stop subscribing to all storages events.

func (*StorageProvider) ReleaseOnExiting

func (sp *StorageProvider) ReleaseOnExiting(diskItem *axstorage.DiskItem)

ReleaseOnExiting releases a DiskItem if it is exiting and has been previously set up. This is a critical operation to ensure resources are properly released before the disk becomes unavailable. It should be invoked as part of the storage management lifecycle, especially when handling storage removal or disconnection events.

func (*StorageProvider) RemoveFile

func (sp *StorageProvider) RemoveFile(di *axstorage.DiskItem, filePath string) *RwResult

RemoveFile deletes the specified file from the disk item. It returns an RwResult indicating the outcome of the remove operation.

func (*StorageProvider) Setup

func (sp *StorageProvider) Setup(diskItem *axstorage.DiskItem) error

Setup prepares a given DiskItem for use by performing necessary initializations such as setting up its directory structure and ensuring it's ready for read/write operations. This method performs asynchronous setup and is intended to be called when the disk is determined to be in a state suitable for setup (e.g., writable and not full).

func (*StorageProvider) Unsubscribe

func (sp *StorageProvider) Unsubscribe(d *axstorage.DiskItem) error

Unsubscribe Stop subscribing to storage events.

func (*StorageProvider) UnsubscribeAll

func (sp *StorageProvider) UnsubscribeAll()

UnsubscribeAll Stop subscribing to all storages events.

func (*StorageProvider) WriteFile

func (sp *StorageProvider) WriteFile(di *axstorage.DiskItem, filePath string, content []byte) *RwResult

WriteFile writes the given content to a file at the specified path on the disk item. It returns an RwResult indicating the outcome of the write operation.

type StreamSelectEvent

type StreamSelectEvent struct {
	Camera                  int
	Width, Height, Rotation int
	IsMirrored              bool
	StreamType              axoverlay.AxOverlayStreamType
}

Jump to

Keyboard shortcuts

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