Rpl_web_logo

Rpl C++ library

v1.2.0

Table of contents

Overview

Rpl C++ library is a software controller for RP Optical Lab Zoom lenses. The Rpl library inherits Lens interfaces. It depends on libraries: Lens (provides interface and data structures to control lenses), Logger (provides functions to print logs), SerialPort (provides functions to work with serial ports), RpLensParser (provides functions to encode control commands and decode responses from Rp lenses; it is a part of the Rpl repository: folder src/parser, see src/parser/README.md) and AFEngine (provides auto focus functions). The library Lens depends on the libraries Frame and ConfigReader, the library AFEngine depends on the library Frame. The repository of the library does not contain the other libraries it depends on: they are cloned next to the repository (see Build and connect to your project section). The Rpl library provides a simple interface to be integrated in any C++ projects. The library repository (folder) is provided by source code and doesn’t have third-party dependencies to be specially installed in the OS. It is developed with C++17 standard and is compatible with Linux and Windows.

Rpl is general-purpose software: it is not tied to any sector or application, and the developer of a program decides what the program does with it.

The library code was developed by reverse engineering the serial port communication protocol of the lenses.

Versions

Table 1 - Library versions.

Version Release date What’s new
1.0.0 12.07.2024 First version.
1.0.1 26.07.2024 - Auto focus function added.
1.0.2 06.08.2024 - Coder reviewed.
- Submodules updated.
1.0.3 11.09.2024 - Add HW limits detection.
1.0.4 16.09.2024 - Update HW limits detection.
- Add FILTER_MODE support.
1.0.5 21.10.2024 - Add zoom / focus response position control.
1.0.6 17.03.2025 - AFEngine Denoiser switched on by default.
1.0.7 03.04.2025 - Logger submodule update.
1.0.8 14.05.2025 - AFEngine submodule update.
1.0.9 26.10.2025 - SerialPort submodule update.
- RpLensParser submodule update.
1.0.10 28.03.2026 - AFEngine submodule update.
1.1.0 01.07.2026 - Critical bugs fixed.
- AFEngine submodule updated.
1.1.1 13.07.2026 - Updated AFEngine submodule.
1.1.2 17.10.2026 - Git submodules removed: the libraries Rpl depends on (Frame, ConfigReader, AFEngine, SerialPort, RpLensParser, Lens, Logger) are expected in the same folder as the repository.
- Fixed crashes: division by zero if ZOOM_HW_MAX_SPEED or FOCUS_HW_MAX_SPEED is set to 0 or if IRIS_HW_OPEN_LIMIT and IRIS_HW_CLOSE_LIMIT are equal, decodeAndExecuteCommand(…) with nullptr.
- Fixed undefined behavior: integer overflow and division by zero in the conversion of the hardware positions, conversion of NaN, locking of the params in the communication thread, setParam(…) and executeCommand(…), counter of responses.
- NaN and infinity values of params and arguments are rejected.
- Command queue is limited (1024 commands).
- End of action responses of the lens update the zoom and focus positions.
- LOG_MODE can be read by getParam(…). FILTER_MODE is limited to 0 - 255. Baud rate and timeout of the initialization string are checked.
- Test application: the lens is controlled by commands typed in the terminal.
- Added compiler warnings and exploit mitigation options to CMake files.
- Documentation corrected.
1.2.0 29.10.2026 - The RpLensParser library is a part of the repository (folder src/parser) and is not a separate dependency any more.

Library files

The library is supplied by source code only. The user is given a set of files in the form of a CMake project (repository). The libraries the library depends on (except RpLensParser, folder src/parser) are not part of the repository (see Build and connect to your project section). The repository structure is shown below:

CMakeLists.txt ------------------------- Main CMake file of the library.
src ------------------------------------ Folder with library source code.
    CMakeLists.txt --------------------- CMake file of the library.
    Rpl.h ------------------------------ Main library header file.
    Rpl.cpp ---------------------------- C++ implementation file.
    RplVersion.h ----------------------- Header file with library version.
    RplVersion.h.in -------------------- CMake file to generate version header.
    parser ----------------------------- Protocol parser library (former RpLensParser repository).
        .gitignore --------------------- Git ignore file of the parser library.
        CMakeLists.txt ----------------- Main CMake file of the parser library.
        README.md ---------------------- Documentation of the parser library.
        src ---------------------------- Folder with source code of the parser library.
            CMakeLists.txt ------------- CMake file of the parser library (target RpLensParser).
            RpLensParser.cpp ----------- C++ implementation file of the parser library.
            RpLensParser.h ------------- Main header file of the parser library (RpLensParser class declaration).
            RpLensParserVersion.h ------ Header file with version of the parser library.
            RpLensParserVersion.h.in --- CMake service file to generate version header of the parser library.
        static ------------------------- Folder with images of the parser documentation.
            rplensparser_web_logo.png -- Logo of the parser library.
        test --------------------------- Folder with test application of the parser (not built by Rpl).
            CMakeLists.txt ------------- CMake file for test application of the parser.
            main.cpp ------------------- Source C++ file of test application of the parser.
test ----------------------------------- Folder with test application files.
    CMakeLists.txt --------------------- CMake file for test application.
    main.cpp --------------------------- Source C++ file of test application.
example -------------------------------- Folder with simple example application.
    CMakeLists.txt --------------------- CMake file for simple example application.
    main.cpp --------------------------- Source C++ file of simple example application.
static --------------------------------- Folder with the logo of the library.

Rpl class description

Rpl class declaration

Rpl.h file contains Rpl class declaration. The class is not copyable and not movable.

namespace rapidpixel
{
/// RP lens controller class.
class Rpl : public Lens
{
public:

    /// Class constructor.
    Rpl();

    /// Class destructor.
    ~Rpl() override;

    /// Get class version.
    static std::string getVersion();

    /// Open lens port.
    bool openLens(std::string initString) override;

    /// Init lens controller.
    bool initLens(LensParams& params) override;

    /// Close serial port and stop communication thread.
    void closeLens() override;

    /// Get controller initialization status.
    bool isLensOpen() override;

    /// Get connection status.
    bool isLensConnected() override;

    /// Set the lens controller parameter.
    bool setParam(LensParam id, float value) override;

    /// Get the lens controller param.
    float getParam(LensParam id) override;

    /// Get the lens controller params.
    void getParams(LensParams& params) override;

    /// Execute command.
    bool executeCommand(LensCommand id, float arg = 0) override;

    /// Add video frame for auto focus purposes.
    void addVideoFrame(rapidpixel::Frame& frame) override;

    /// Decode and execute command.
    bool decodeAndExecuteCommand(uint8_t* data, int size) override;
};
}

The methods setParam(…), getParam(…), getParams(…), executeCommand(…), addVideoFrame(…), decodeAndExecuteCommand(…), isLensOpen() and isLensConnected() are thread-safe. The methods openLens(…) and closeLens() are serialized by the class: only one of them works at a time. The methods do not throw exceptions.

getVersion method

The getVersion() method returns a string of the current version of Rpl class. Method declaration:

static std::string getVersion();

Method can be used without Rpl class instance. Example:

std::cout << "Rpl version: " << rapidpixel::Rpl::getVersion() << std::endl;

Console output:

Rpl version: 1.2.0

openLens method

The openLens(…) method opens the serial port to communicate with Rp lenses and runs the communication thread. If the lens is already open, the method returns TRUE without any changes. The method does not change the lens params except initString and the open status. The communication thread requests the lens position, decodes the responses of the lens and detects the hardware limits of zoom and focus: the controller moves zoom to tele and focus to far (a limit is reached when the position does not change for 500 ms), sets the params ZOOM_HW_TELE_LIMIT and FOCUS_HW_FAR_LIMIT and returns zoom and focus to the initial positions. The commands set by setParam(…) and executeCommand(…) wait until the detection is finished (the detection is not finished if the lens does not respond). Method declaration:

bool openLens(std::string initString) override;
Parameter Value
initString Initialization string contains the full serial port name, baud rate, timeout separated by “;”. Example: “/dev/ttyUSB0;19200;50”. Baud rate (must be a number > 0) and timeout of waiting for lens data in milliseconds (must be a number >= 0) are optional params: the default values are 19200 and 50. Empty fields are skipped.

Returns: TRUE if the lens controller is initialized or FALSE if not: the initialization string has no serial port name, the baud rate or the timeout is not valid, the serial port can’t be opened or the communication thread can’t be started.

initLens method

The initLens(…) initializes the lens controller and sets lens params (Lens interface). The method sets the given lens params and then calls the openLens(…) method. A value which is not valid for the controller (see setParam(…)) is ignored: the default value of the param is kept. Params which are not supported by the controller are ignored. After successful initialization, the library will run communication threads (thread to communicate with equipment via serial port) if it has not run before. Method declaration:

bool initLens(LensParams& params) override;
Parameter Value
params LensParams class object which includes all lens parameters. LensParams class includes initString which is used in openLens(…) method. See description of LensParams class.

Returns: TRUE if the lens controller is initialized or FALSE if not.

closeLens method

The closeLens() closes the serial port and stops the communication thread. If the lens is not open the method does nothing. Commands which were queued but not sent to the lens stay in the queue and are sent after the next openLens(…) (after the detection of the hardware limits). Method declaration:

void closeLens() override;

isLensOpen method

The isLensOpen() method returns the lens controller initialization status. Open status shows if the controller is initialized (serial port open) but doesn’t show if the controller has communication with equipment. For example, if the serial port is open (opens serial port file in OS) but equipment can be not active (no power). In this case, the open status just shows that the serial port is open. Method declaration:

bool isLensOpen() override;

Returns: TRUE if the lens controller is initialized or FALSE if not.

isLensConnected method

The isLensConnected() method shows if the lens controller receives responses from equipment. For example, if the serial port is open but equipment is not active (no power). In this case, the method isLensOpen(…) will return TRUE but isLensConnected() method will return FALSE. The status is FALSE if the lens did not respond to 11 consecutive reads of the serial port (the read timeout is set by the initialization string). Method declaration:

bool isLensConnected() override;

Returns: TRUE if the lens controller has data exchange with lens equipment or FALSE if not.

setParam method

The setParam(…) method sets a new lens parameter value. Rpl provides a thread-safe setParam(…) method call. This means that the setParam(…) method can be safely called from any thread. The commands for the lens (for example, the commands which move zoom or focus) are put in the command queue and sent by the communication thread in the order of the calls, so the method does not wait for the lens. The queue keeps not more than 1024 commands. Valid values of the params are described in LensParam section (Table 3). A value outside of the valid range, NaN and infinity are not accepted. Method declaration:

bool setParam(LensParam id, float value) override;
Parameter Description
id Lens parameter ID according to LensParam enum.
value Lens parameter value. Value depends on parameter ID (LensParam enum).

Returns: TRUE if the parameter was set or FALSE if not: the value is not valid, the parameter is not supported or can’t be set (read only), the command queue is full or there is not enough memory. If the method returns FALSE the lens controller is not changed.

getParam method

The getParam(…) method returns a lens parameter value. Rpl provides a thread-safe getParam(…) method call. This means that the getParam(…) method can be safely called from any thread. The values of the positions and the speeds are the values reported by the lens. Method declaration:

float getParam(LensParam id) override;
Parameter Description
id Lens parameter ID according to LensParam enum.

Returns: parameter value or -1 if the parameter doesn’t exist (not supported, see Table 3).

getParams method

The getParams(…) method returns a lens parameters class. Rpl provides a thread-safe getParams(…) method call. This means that the getParams(…) method can be safely called from any thread. The field fovPoints is not supported and is not changed. If there is not enough memory to copy the params the object is not changed. Method declaration:

void getParams(LensParams& params) override;
Parameter Description
params Reference to a LensParams class object which includes all lens parameters.

executeCommand method

The executeCommand(…) method executes a lens action command. Rpl provides a thread-safe executeCommand(…) method call. This means that the executeCommand(…) method can be safely called from any thread. The commands for the lens are put in the command queue and sent by the communication thread in the order of the calls (not more than 1024 commands wait in the queue). The commands ZOOM_TO_POS, FOCUS_TO_POS and IRIS_TO_POS use the argument (position 0 - 65535): NaN, infinity and values outside of the range are not accepted. Method declaration:

bool executeCommand(LensCommand id, float arg = 0) override;
Parameter Description
id Lens action command ID according to LensCommand enum.
arg Lens action command argument. Value depends on command ID (see description of LensCommand enum).

Returns: TRUE if the command was executed (accepted by lens controller) or FALSE if not: the argument is not valid, the command is not supported, the command queue is full or there is not enough memory.

addVideoFrame method

The addVideoFrame(…) method copies video frame data to the lens controller to perform an autofocus algorithm. To perform autofocus, the lens controller calculates the focus factor in the autofocus ROI (focus factor can be obtained with the method getParam(…) and parameter FOCUS_FACTOR). To calculate the focus factor, Rpl needs a video frame, so to use auto focus functions, the method addVideoFrame(…) must be called for each captured video frame. If the autofocus ROI is in manual mode (AF_ROI_MODE is 0) and is not set, the method sets it to the central part of the frame (CUSTOM_1 percent of the frame size). Method declaration:

void addVideoFrame(rapidpixel::Frame& frame) override;
Parameter Description
frame Video frame object (see Frame class description).

decodeAndExecuteCommand method

The decodeAndExecuteCommand(…) method decodes and executes a command on the controller side. The method will decode commands which are encoded by the encodeCommand(…) and encodeSetParamCommand(…) methods of Lens interface classes. If a command is decoded, the method will call setParam(…) or executeCommand(…) methods for lens interfaces. This method is thread-safe. This means that the method can be safely called from any thread. Method declaration:

bool decodeAndExecuteCommand(uint8_t* data, int size) override;
Parameter Description
data Pointer to input command. Must not be nullptr. To generate an input command, you may use the encodeCommand(…) and encodeSetParamCommand(…) methods.
size Size of the command. Must be 11 bytes for SET_PARAM and COMMAND.

Returns: TRUE if the command is decoded (SET_PARAM or COMMAND) and executed (action command or set param command) or FALSE if not: the command is not valid (see decodeCommand(…)) or setParam(…) or executeCommand(…) returned FALSE.

encodeSetParamCommand method of Lens class

The encodeSetParamCommand(…) static method designed to encode command to change any remote lens parameter. To control a lens remotely, the developer has to develop his own protocol and according to it encode the command and deliver it over the communication channel. To simplify this, the Lens class contains static methods for encoding the control command. The Lens class provides two types of commands: a parameter change command (SET_PARAM) and an action command (COMMAND). encodeSetParamCommand(…) designed to encode SET_PARAM command. Method declaration:

static void encodeSetParamCommand(uint8_t* data, int& size, LensParam id, float value);
Parameter Description
data Pointer to data buffer for encoded command. Must have size >= 11. Must not be nullptr.
size Size of encoded data. Will be 11 bytes (0 if data is nullptr).
id Parameter ID according to LensParam enum.
value Parameter value.

encodeSetParamCommand(…) is static and used without Lens class instance. This method used on client side (control system). Example:

// Buffer for encoded data.
uint8_t data[11];
// Size of encoded data.
int size = 0;
// Parameter value.
float value = 10.0f;
// Encode command.
rapidpixel::Lens::encodeSetParamCommand(
    data, size, rapidpixel::LensParam::AF_ROI_X0, value);

encodeCommand method of Lens class

The encodeCommand(…) static method designed to encode lens action command. To control a lens remotely, the developer has to develop his own protocol and according to it encode the command and deliver it over the communication channel. To simplify this, the Lens class contains static methods for encoding the control command. The Lens class provides two types of commands: a parameter change command (SET_PARAM) and an action command (COMMAND). encodeCommand(…) designed to encode COMMAND command (action command). Method declaration:

static void encodeCommand(uint8_t* data, int& size, LensCommand id, float arg = 0.0f);
Parameter Description
data Pointer to data buffer for encoded command. Must have size >= 11. Must not be nullptr.
size Size of encoded data. Will be 11 bytes (0 if data is nullptr).
id Command ID according to LensCommand enum.
arg Command argument value (value depends on command ID).

encodeCommand(…) is static and used without Lens class instance. This method used on client side (control system). Encoding example:

// Buffer for encoded data.
uint8_t data[11];
// Size of encoded data.
int size = 0;
// Command argument value.
float arg = 1000.0f;
// Encode command.
rapidpixel::Lens::encodeCommand(
    data, size, rapidpixel::LensCommand::ZOOM_TO_POS, arg);

decodeCommand method of Lens class

The decodeCommand(…) static method designed to decode command on lens controller side. To control a lens remotely, the developer has to develop his own protocol and according to it decode the command on lens controller side. To simplify this, the Lens interface class contains static method to decode input command (commands should be encoded by encodeSetParamCommand(…) or encodeCommand(…) methods). The Lens class provides two types of commands: a parameter change command (SET_PARAM) and an action command (COMMAND). Method declaration:

static int decodeCommand(uint8_t* data, int size, LensParam& paramId, LensCommand& commandId, float& value);
Parameter Description
data Pointer to input command. Must not be nullptr.
size Size of command. Must be exactly 11 bytes.
paramId Lens parameter ID according to LensParam enum. After decoding SET_PARAM command the method will return parameter ID. The argument is not changed in other cases.
commandId Lens command ID according to LensCommand enum. After decoding COMMAND the method will return command ID. The argument is not changed in other cases.
value Lens parameter value (after decoding SET_PARAM command) or lens command argument (after decoding COMMAND). The value is not checked against any range: lens controller must validate it before use. The argument is changed only if the command was decoded.

Returns: 0 - in case decoding COMMAND, 1 - in case decoding SET_PARAM command or -1 in case errors: data is nullptr, size is not 11, version (Major and Minor) of the command is not equal to the version of the library, the command type is unknown, the command ID or the parameter ID is outside of the range of LensCommand or LensParam enum. If the method returns -1 the output arguments are not changed.

Data structures

LensCommand enum

Enum declaration:

namespace rapidpixel
{
/**
 * @brief Lens commands enum.
 *
 * The IDs are consecutive and start from 1. Lens::decodeCommand(...) accepts
 * the IDs from ZOOM_TELE to the last enumerator (DETECT_HW_RANGES). A command
 * added to the enum must be placed at the end, and the check in Lens.cpp must
 * use the last enumerator.
 */
enum class LensCommand
{
    /// Move zoom tele (in). Command doesn't have arguments. User should be able
    /// to set zoom movement speed via lens parameters.
    ZOOM_TELE = 1,
    /// Move zoom wide (out). Command doesn't have arguments. User should be
    /// able to set zoom movement speed via lens parameters.
    ZOOM_WIDE,
    /// Move zoom to position. Lens controller should have zoom range from
    /// 0 (full wide) to 65535 (full tele) regardless of the hardware value of
    /// the zoom position. If the minimum and maximum zoom position limits are
    /// set by the user in the lens parameters, the range of the hardware zoom
    /// position must be scaled to the user space 0-65535 range.
    /// Command argument: zoom position 0-65535. User should be able to set zoom
    /// movement speed via lens parameters.
    ZOOM_TO_POS,
    /// Stop zoom moving including stop zoom to position command.
    ZOOM_STOP,
    /// Move focus far. Command doesn't have arguments. User should be able to
    /// set focus movement speed via lens parameters.
    FOCUS_FAR,
    /// Move focus near. Command doesn't have arguments. User should be able to
    /// set focus movement speed via lens parameters.
    FOCUS_NEAR,
    /// Move focus to position. Lens controller should have focus range from 0
    /// (full near) to 65535 (full far) regardless of the hardware value of the
    /// focus position. If the minimum and maximum focus position limits are
    /// set by the user in the lens parameters, the range of the hardware focus
    /// position must be scaled to the 0-65535 user space range.
    /// Command argument: focus position 0-65535. User should be able to set
    /// focus movement speed via lens parameters.
    FOCUS_TO_POS,
    /// Stop focus moving including stop focus to position command.
    FOCUS_STOP,
    /// Move iris open. Command doesn't have arguments. User should be able to
    /// set iris movement speed via lens parameters.
    IRIS_OPEN,
    /// Move iris close. Command doesn't have arguments. User should be able
    /// to set iris movement speed via lens parameters.
    IRIS_CLOSE,
    /// Move iris to position. Lens controller should have iris range
    /// from 0 (full close) to 65535 (full far) regardless of the hardware
    /// value of the iris position. If the minimum and maximum iris position
    /// limits are set by the user in the lens parameters, the range of the
    /// hardware iris position must be scaled to the 0-65535 user space range.
    /// Command argument: iris position 0-65535. User should be able to set
    /// iris movement speed via lens parameters.
    IRIS_TO_POS,
    /// Stop iris moving including stop iris to position command.
    /// Command doesn't have arguments.
    IRIS_STOP,
    /// Start autofocus.  Command doesn't have arguments.
    AF_START,
    /// Stop autofocus.  Command doesn't have arguments.
    AF_STOP,
    /// Restart lens controller.
    RESTART,
    /// Detect zoom and focus hardware ranges. After execution this command the
    /// lens controller should automatically set at least parameters
    /// (LensParam enum): ZOOM_HW_TELE_LIMIT, ZOOM_HW_WIDE_LIMIT,
    /// FOCUS_HW_FAR_LIMIT and FOCUS_HW_NEAR_LIMIT.
    DETECT_HW_RANGES
};
}

Table 2 - Lens commands description. Some commands may be unsupported by lens controller.

Command Description
ZOOM_TELE Move zoom tele (in). Command doesn’t have arguments. Zoom speed can be set by setParam(…) method.
ZOOM_WIDE Move zoom wide (out). Command doesn’t have arguments. Zoom speed can be set by setParam(…) method.
ZOOM_TO_POS Move zoom to position. Command argument: zoom position 0 (full wide) - 65535 (full tele). Zoom speed can be set by setParam(…) method.
ZOOM_STOP Stop zoom moving including stop zoom to position command. Command doesn’t have arguments.
FOCUS_FAR Move focus far. Command doesn’t have arguments. Focus speed can be set by setParam(…) method.
FOCUS_NEAR Move focus near. Command doesn’t have arguments. Focus speed can be set by setParam(…) method.
FOCUS_TO_POS Move focus to position. Command argument: focus position 0 (full near) - 65535 (full far). Focus speed can be set by setParam(…) method.
FOCUS_STOP Stop focus moving including stop focus to position command. Command doesn’t have arguments.
IRIS_OPEN Move iris open. Command doesn’t have arguments.
IRIS_CLOSE Move iris close. Command doesn’t have arguments.
IRIS_TO_POS Move iris to position. Command argument: iris position 0 (full close) - 65535 (full open).
IRIS_STOP Stop iris.
AF_START Start autofocus (the param FOCUS_MODE must be 1 or 2). Command doesn’t have arguments. Video frames must be added by addVideoFrame(…).
AF_STOP Stop autofocus. Command doesn’t have arguments.
RESTART Not supported by Rpl class.
DETECT_HW_RANGES Calibrate the autofocus engine: the engine measures the delay between the lens position and the video frame and sets the param CUSTOM_2 (time adjustment). Command doesn’t have arguments. Video frames must be added by addVideoFrame(…).

LensParam enum

Enum declaration:

namespace rapidpixel
{
/**
 * @brief Lens params enum.
 *
 * The IDs are consecutive and start from 1. Lens::decodeCommand(...) accepts
 * the IDs from ZOOM_POS to the last enumerator (CUSTOM_3). A param added to
 * the enum must be placed at the end, and the check in Lens.cpp must use the
 * last enumerator.
 */
enum class LensParam
{
    /// Zoom position. Setting a parameter is equivalent to the command
    /// ZOOM_TO_POS. Lens controller should have zoom range from 0 (full wide)
    /// to 65535 (full tele) regardless of the hardware value of the zoom
    /// position. If the minimum and maximum zoom position limits are set by
    /// the user in the lens parameters, the range of the hardware zoom position
    /// must be scaled to the user space 0-65535 range. Parameter value: zoom
    /// position 0-65535. User should be able to set zoom movement speed via
    /// lens parameters.
    ZOOM_POS = 1,
    /// Hardware zoom position. Parameter value depends on implementation and
    /// lens hardware.
    ZOOM_HW_POS,
    /// Focus position. Setting a parameter is equivalent to the command
    /// FOCUS_TO_POS. Lens controller should have focus range from 0 (full near)
    /// to 65535 (full far) regardless of the hardware value of the focus
    /// position. If the minimum and maximum focus position limits are set by
    /// the user in the lens parameters, the range of the hardware focus
    /// position must be scaled to the 0-65535 user space range. Parameter
    /// value: focus position 0-65535. User should be able to set focus movement
    /// speed via lens parameters.
    FOCUS_POS,
    /// Hardware focus position. Parameter value depends on implementation and
    /// lens hardware.
    FOCUS_HW_POS,
    /// Iris position. Setting a parameter is equivalent to the command
    /// IRIS_TO_POS. Lens controller should have iris range from 0 (full close)
    /// to 65535 (full far) regardless of the hardware value of the iris
    /// position. If the minimum and maximum iris position limits are set by the
    /// user in the lens parameters, the range of the hardware iris position
    /// must be scaled to the 0-65535 user space range. Parameter value: iris
    /// position 0-65535. User should be able to set iris movement speed via
    /// lens parameters.
    IRIS_POS,
    /// Hardware iris position. Parameter value depends on particular lens
    /// controller.
    IRIS_HW_POS,
    /// Focus mode. Parameter value depends on implementation but it is
    /// recommended to keep default values: 0 - Manual focus control,
    /// 1 - Auto focus control.
    FOCUS_MODE,
    /// Filter mode. Parameter value depends on implementation but it is
    /// recommended to keep default values: 0 - Filter on, 1 - Filter off.
    FILTER_MODE,
    /// Autofocus ROI top-left corner horizontal position in pixels.
    /// Autofocus ROI is rectangle.
    AF_ROI_X0,
    /// Autofocus ROI top-left corner vertical position in pixels.
    /// Autofocus ROI is rectangle.
    AF_ROI_Y0,
    /// Autofocus ROI bottom-right corner horizontal position in pixels.
    /// Autofocus ROI is rectangle.
    AF_ROI_X1,
    /// Autofocus ROI bottom-right corner vertical position in pixels.
    /// Autofocus ROI is rectangle.
    AF_ROI_Y1,
    /// Zoom speed. Lens controller should have zoom speed range from 0 to
    /// 100% of max hardware zoom speed (parameter ZOOM_HW_MAX_SPEED).
    /// If the user sets a new parameter value of the ZOOM_HW_SPEED the
    /// parameter ZOOM_SPEED must be updated automatically. Formula for
    /// calculating speed:
    /// ZOOM_SPEED = ( ZOOM_HW_SPEED / ZOOM_HW_MAX_SPEED) * 100.
    ZOOM_SPEED,
    /// Zoom hardware speed. Value depends on implementation and lens hardware.
    /// The value of the parameters must be <= ZOOM_HW_MAX_SPEED parameter.
    /// If the user sets a new parameter value of the ZOOM_SPEED parameter
    /// the parameter ZOOM_HW_SPEED must be updated automatically.
    /// Formula for calculating hardware speed:
    /// ZOOM_HW_SPEED = ( ZOOM_SPEED / 100 ) * ZOOM_HW_MAX_SPEED.
    ZOOM_HW_SPEED,
    /// Maximum zoom hardware speed. Value depends on implementation.
    /// If user sets new ZOOM_HW_MAX_SPEED value the parameters
    /// ZOOM_SPEED must be updated automatically. If new value of
    /// ZOOM_HW_MAX_SPEED parameter will be less than ZOOM_HW_SPEED the
    /// parameter ZOOM_HW_SPEED must be reduced automatically.
    ZOOM_HW_MAX_SPEED,
    /// Focus speed. Lens controller should have focus speed range from 0 to
    /// 100% of max hardware focus speed (parameter FOCUS_HW_MAX_SPEED).
    /// If the user sets a new parameter value of the FOCUS_HW_SPEED the
    /// parameter FOCUS_SPEED must be updated automatically. Formula for
    /// calculating speed: FOCUS_SPEED = ( FOCUS_HW_SPEED / FOCUS_HW_MAX_SPEED)
    /// * 100.
    FOCUS_SPEED,
    /// Focus hardware speed. Value depends on on implementation and lens
    /// hardware. The value of the parameters must be <= FOCUS_HW_MAX_SPEED
    /// parameter. If the user sets a new parameter value of the FOCUS_SPEED
    /// parameter the parameter FOCUS_HW_SPEED must be updated automatically.
    /// Formula for calculating hardware speed:
    /// FOCUS_HW_SPEED = ( FOCUS_SPEED / 100 ) * FOCUS_HW_MAX_SPEED.
    FOCUS_HW_SPEED,
    /// Maximum focus hardware speed. Value depends on implementation.
    /// If user sets new FOCUS_HW_MAX_SPEED value the parameters
    /// FOCUS_SPEED and FOCUS_HW_SPEED must be updated by lens controller
    /// automatically. If new value of FOCUS_HW_MAX_SPEED parameter will be
    /// less than FOCUS_HW_SPEED the parameter FOCUS_HW_SPEED must be reduced
    /// automatically.
    FOCUS_HW_MAX_SPEED,
    /// Iris speed. Lens controller should have iris speed range from 0 to 100%
    /// of max hardware iris speed (parameter IRIS_HW_MAX_SPEED). If the user
    /// sets a new parameter value of the IRIS_HW_SPEED the parameter IRIS_SPEED
    /// must be updated automatically. Formula for calculating speed:
    /// IRIS_SPEED = ( IRIS_HW_SPEED / IRIS_HW_MAX_SPEED) * 100.
    IRIS_SPEED,
    /// Iris hardware speed. Value depends on implementation and lens hardware.
    /// The value of the parameters must be <= IRIS_HW_MAX_SPEED parameter.
    /// If the user sets a new parameter value of the IRIS_SPEED parameter
    /// the parameter IRIS_HW_SPEED must be updated automatically. Formula
    /// for calculating hardware speed:
    /// IRIS_HW_SPEED = ( IRIS_SPEED / 100 ) * IRIS_HW_MAX_SPEED.
    IRIS_HW_SPEED,
    /// Maximum iris hardware speed. Value depends on implementation. If user
    /// sets new IRIS_HW_MAX_SPEED value the parameters IRIS_SPEED and
    /// IRIS_HW_SPEED must be updated automatically. If new value of
    /// IRIS_HW_MAX_SPEED parameter will be less than IRIS_HW_SPEED the
    /// parameter IRIS_HW_SPEED must be reduced automatically.
    IRIS_HW_MAX_SPEED,
    /// Zoom hardware tele limit. Value depends on implementation and lens
    /// hardware. Lens controller should control zoom position. Lens controller
    /// should stop zoom moving if hardware zoom position will be out of limits.
    ZOOM_HW_TELE_LIMIT,
    /// Zoom hardware wide limit. Value depends on implementation and lens
    /// hardware. Lens controller should control zoom position. Lens controller
    /// should stop zoom moving if hardware zoom position will be out of limits.
    ZOOM_HW_WIDE_LIMIT,
    /// Focus hardware far limit. Value depends on on implementation and lens
    /// hardware. Lens controller should control focus position. Lens controller
    /// should stop focus moving if hardware focus position will be out of
    /// limits.
    FOCUS_HW_FAR_LIMIT,
    /// Focus hardware near limit. Value depends on implementation and lens
    /// hardware. Lens controller should control focus position. Lens controller
    /// should stop focus moving if hardware focus position will be out of
    /// limits.
    FOCUS_HW_NEAR_LIMIT,
    /// Iris hardware open limit. Value depends on implementation and lens
    /// hardware. Lens controller should control iris position. Lens controller
    /// should stop iris moving if hardware iris position will be out of limits.
    IRIS_HW_OPEN_LIMIT,
    /// Iris hardware close limit. Value depends on implementation and lens
    /// hardware. Lens controller should control iris position. Lens controller
    /// should stop iris moving if hardware iris position will be out of limits.
    IRIS_HW_CLOSE_LIMIT,
    /// Focus factor if it was calculated. If not calculated must be -1.
    /// Value depends on particular lens controller.
    FOCUS_FACTOR,
    /// Lens connection status. Connection status shows if the lens controller
    /// has data exchange with lens equipment. For example, if lens has serial
    /// port lens controller connects to serial port
    /// (opens serial port file in OS) but lens can be not active (no power).
    /// In this case connection status shows that lens controller doesn't have
    /// data exchange with lens equipment (the value is 0). If lens controller
    /// has data exchange with lens equipment the value is 1. If lens controller
    /// not initialize the connection status always FALSE. Value: 0 - not
    /// connected. 1 - connected.
    IS_CONNECTED,
    /// Focus hardware speed in autofocus mode. Value depends on implementation
    /// and lens hardware.
    FOCUS_HW_AF_SPEED,
    /// Threshold for changes of focus factor to start refocus. Value:
    /// 0% - no check, 100% - changing x2.
    FOCUS_FACTOR_THRESHOLD,
    /// Timeout for automatic refocus in seconds. Value:
    /// 0 - no automatic refocus, 100000 - maximum value.
    REFOCUS_TIMEOUT_SEC,
    /// Flag about active autofocus algorithm. Value: 0 - autofocus not working,
    /// 1 - working.
    AF_IS_ACTIVE,
    /// Iris mode. Value depends on implementation but it is recommended to keep
    /// default values: 0 - manual iris control, 1 - auto iris control.
    IRIS_MODE,
    /// ROI width (pixels) for autofocus algorithm when lens controller detects
    /// ROI position automatically. Value: from 8 to (video frame width -
    /// AUTO_AF_ROI_BORDER * 2).
    AUTO_AF_ROI_WIDTH,
    /// ROI height (pixels) for autofocus algorithm when lens controller
    /// detects ROI position automatically. Value: from 8 to
    /// (video frame height - AUTO_AF_ROI_BORDER * 2).
    AUTO_AF_ROI_HEIGHT,
    /// Video frame border size (along vertical and horizontal axes).
    /// Value: border size from 0 to video frame
    /// min(video frame width/height) / 2.
    AUTO_AF_ROI_BORDER,
    /// AF ROI mode (write/read). Value: 0 - Manual position, 1 - Auto position.
    AF_ROI_MODE,
    /// Lens extender mode. Value depends on implementation but it is
    /// recommended to keep default values: 0 - no extender, 1 - x2 extender.
    EXTENDER_MODE,
    /// Lens stabilization mode. Value depends on implementation but it is
    /// recommended to keep default values: 0 - no stabilization,
    /// 1 - stabilization.
    STABILIZER_MODE,
    /// Autofocus range. Value depends on implementation.
    AF_RANGE,
    /// Current horizontal Field of view, degree. Field of view calculated by
    /// lens controller according to initial params or by reading directly from
    /// lens hardware.
    X_FOV_DEG,
    /// Current vertical Field of view, degree. Field of view calculated by lens
    /// controller according to initial params or by reading directly from lens
    /// hardware.
    Y_FOV_DEG,
    /// Logging mode. Values: 0 - Disable, 1 - Only file, 2 - Only terminal,
    /// 3 - File and terminal.
    LOG_MODE,
    /// Lens temperature, degree.
    TEMPERATURE,
    /// Lens controller initialization status. Open status shows if the lens
    /// controller initialized or not but doesn't show if lens controller has
    /// communication with lens equipment. For example, if lens has serial port
    /// lens controller connects to serial port (opens serial port file in OS)
    /// but lens can be not active (no power). In this case open status just
    /// shows that lens controller has opened serial port. Values: 0 - not open
    /// (not initialized), 1 - open (initialized).
    IS_OPEN,
    /// Lens type. Value depends on implementation. Type allows to lens
    /// initialize necessary parameters for particular lens hardware.
    TYPE,
    /// Lens custom parameter. Value depends on particular lens controller.
    /// Custom parameters used when particular lens equipment has specific
    /// unusual parameter.
    CUSTOM_1,
    /// Lens custom parameter. Value depends on particular lens controller.
    /// Custom parameters used when particular lens equipment has specific
    /// unusual parameter.
    CUSTOM_2,
    /// Lens custom parameter. Value depends on particular lens controller.
    /// Custom parameters used when particular lens equipment has specific
    /// unusual parameter.
    CUSTOM_3
};
}

Table 3 - Lens params description. Some params may be unsupported by lens controller.

Parameter Access Description
ZOOM_POS read / write Zoom position. Setting a parameter is equivalent to the command ZOOM_TO_POS. Param argument: zoom position 0 (full wide) - 65535 (full tele). Zoom speed can be set by setParam(…) method. It doesn’t change the zoom position value immediately. The zoom position changes only when the lens moves.
ZOOM_HW_POS read / write Hardware zoom position. Setting a parameter move zoom to HW position. Param argument: zoom position ZOOM_HW_WIDE_LIMIT - ZOOM_HW_TELE_LIMIT. By default ZOOM_HW_WIDE_LIMIT = 0, ZOOM_HW_TELE_LIMIT = 64000. Zoom speed can be set by setParam(…) method. It doesn’t change the zoom position value immediately. The zoom position changes only when the lens moves.
FOCUS_POS read / write Focus position. Setting a parameter is equivalent to the command FOCUS_TO_POS. Parameter value: focus position 0 (full near) - 65535 (full far). Focus speed can be set by setParam(…) method. It doesn’t change the focus position value immediately. The focus position changes only when the lens moves.
FOCUS_HW_POS read / write Focus position. Setting a parameter move focus to HW position. Parameter value: focus position FOCUS_HW_NEAR_LIMIT - FOCUS_HW_FAR_LIMIT. By default FOCUS_HW_NEAR_LIMIT = 0, FOCUS_HW_FAR_LIMIT = 64000. Focus speed can be set by setParam(…) method. It doesn’t change the focus position value immediately. The focus position changes only when the lens moves.
IRIS_POS read / write Iris position. Setting a parameter is equivalent to the command IRIS_TO_POS. Parameter value: iris position 0 (full close) - 65535 (full open). It doesn’t change the iris position value immediately. The iris position changes only when the lens moves.
IRIS_HW_POS read / write Iris position. Setting a parameter move iris to HW position. Parameter value: iris position IRIS_HW_OPEN_LIMIT - IRIS_HW_CLOSE_LIMIT **. By default **IRIS_HW_CLOSE_LIMIT = 0, IRIS_HW_OPEN_LIMIT = 32000. It doesn’t change the iris position value immediately. The iris position changes only when the lens moves.
FOCUS_MODE read / write Focus mode:
0 - Manual focus control.
1 - Push auto focus mode.
2 - Continuous auto focus mode.
FILTER_MODE read / write Filter mode (number of the filter). Value: 0 - 255.
AF_ROI_X0 read / write Autofocus ROI top-left corner horizontal position in pixels. Autofocus ROI is rectangle.
AF_ROI_Y0 read / write Autofocus ROI top-left corner vertical position in pixels. Autofocus ROI is rectangle.
AF_ROI_X1 read / write Autofocus ROI bottom-right corner horizontal position in pixels. Autofocus ROI is rectangle.
AF_ROI_Y1 read / write Autofocus ROI bottom-right corner vertical position in pixels. Autofocus ROI is rectangle.
ZOOM_SPEED read / write Zoom speed. Zoom speed range from 0 to 100 which means 0 -100% of max hardware zoom speed. If the user sets a new parameter value of the ZOOM_HW_SPEED the parameter ZOOM_SPEED updated automatically.
ZOOM_HW_SPEED read / write Zoom hardware speed. Zoom hardware speed range from 0 to ZOOM_HW_MAX_SPEED (7 by default). If the user sets a new parameter value of the ZOOM_SPEED parameter the parameter ZOOM_HW_SPEED updated automatically.
ZOOM_HW_MAX_SPEED read / write Maximum zoom hardware speed. Value: 0 - 7. If the user sets a new parameter value of the ZOOM_HW_MAX_SPEED parameter the parameter ZOOM_SPEED updated automatically.
FOCUS_SPEED read / write Focus speed. Focus speed range from 0 to 100 which means 0 -100% of max hardware focus speed. If the user sets a new parameter value of the FOCUS_HW_SPEED the parameter FOCUS_SPEED updated automatically.
FOCUS_HW_SPEED read / write Focus hardware speed. Focus hardware speed range from 0 to FOCUS_HW_MAX_SPEED (7 by default). If the user sets a new parameter value of the FOCUS_SPEED parameter the parameter FOCUS_HW_SPEED updated automatically.
FOCUS_HW_MAX_SPEED read / write Maximum focus hardware speed. Value: 0 - 7. If the user sets a new parameter value of the FOCUS_HW_MAX_SPEED parameter the parameter FOCUS_SPEED updated automatically.
IRIS_SPEED read / write Not supported by Rpl class.
IRIS_HW_SPEED read / write Not supported by Rpl class.
IRIS_HW_MAX_SPEED read / write Not supported by Rpl class.
ZOOM_HW_TELE_LIMIT read / write Zoom hardware tele limit. Value: ZOOM_HW_WIDE_LIMIT - 64000. Default value 64000. The controller sets the value when it detects the hardware limit.
ZOOM_HW_WIDE_LIMIT read / write Zoom hardware wide limit. Value: 0 - ZOOM_HW_TELE_LIMIT. Default value 0.
FOCUS_HW_FAR_LIMIT read / write Focus hardware far limit. Value: FOCUS_HW_NEAR_LIMIT - 64000. Default value 64000. The controller sets the value when it detects the hardware limit.
FOCUS_HW_NEAR_LIMIT read / write Focus hardware near limit. Value: 0 - FOCUS_HW_FAR_LIMIT. Default value 0.
IRIS_HW_OPEN_LIMIT read / write Iris hardware open limit. Value: IRIS_HW_CLOSE_LIMIT - 32000. Default value 32000.
IRIS_HW_CLOSE_LIMIT read / write Iris hardware close limit. Value: 0 - IRIS_HW_OPEN_LIMIT. Default value 0.
FOCUS_FACTOR read only Focus factor if it was calculated, otherwise -1.
IS_CONNECTED read only Lens connection status. Connection status shows if the lens controller has data exchange with lens equipment. Values:
0 - no response from lens.
1 - connected.
FOCUS_HW_AF_SPEED read only Focus hardware speed in autofocus mode. Default value 2.
FOCUS_FACTOR_THRESHOLD read / write Threshold for changes of focus factor to start refocus. Values: 0% - no check, 100% - changing x2.
REFOCUS_TIMEOUT_SEC read / write Timeout for automatic refocus in seconds. Value: 0 - no automatic refocus, 1000 - maximum value.
AF_IS_ACTIVE read only Flag about active autofocus algorithm. Value: 0 - autofocus not working, 1 - working.
IRIS_MODE read / write Not supported by Rpl class.
AUTO_AF_ROI_WIDTH read / write ROI width (pixels) for autofocus algorithm when lens controller detects ROI position automatically. Value: from 8 to (video frame width - AUTO_AF_ROI_BORDER * 2).
AUTO_AF_ROI_HEIGHT read / write ROI height (pixels) for autofocus algorithm when lens controller detects ROI position automatically. Value: from 8 to (video frame height - AUTO_AF_ROI_BORDER * 2).
AUTO_AF_ROI_BORDER read / write Video frame border size (along vertical and horizontal axes). Value: 0 - 2048 (the value is checked by the autofocus engine). The ROI position is detected only if the border is not more than a quarter of the video frame width and height.
AF_ROI_MODE read / write Auto focus ROI mode. Values:
0 - Manual position.
1 - Auto position. The controller will detect “optimal” auto focus ROI position.
EXTENDER_MODE read / write Not supported by Rpl class.
STABILIZER_MODE read / write Not supported by Rpl class.
AF_RANGE read / write Not supported by Rpl class.
X_FOV_DEG read / write Not supported by Rpl class.
Y_FOV_DEG read / write Not supported by Rpl class.
LOG_MODE read / write Logging mode. Values:
0 - Disable.
1 - Only terminal.
2 - Only file.
3 - File and terminal.
The messages of the library are written to the log file only if the file name and the folder are set by the Logger library.
TEMPERATURE read only Lens temperature, degree.
IS_OPEN read only Lens controller initialization status. Open status shows if the lens controller initialized or not but doesn’t show if lens controller has communication with lens equipment. Values:
0 - not open (not initialized).
1 - open (initialized).
TYPE read / write Not supported by Rpl class.
CUSTOM_1 read / write Percent of central ROI for AF Engine. Value: 1-100.
CUSTOM_2 read / write Time adjustment for AF Engine, ms. Value: -500 - 500.
CUSTOM_3 read / write Not supported by Rpl class.

LensParams class description

LensParams class used for lens controller initialization (initLens(…) method) or to get all actual params (getParams() method). Also LensParams provides structure to write/read params from JSON files (JSON_READABLE macro) and provides methods to encode and decode params.

LensParams class declaration

LensParams interface class declared in Lens.h file. Class declaration:

namespace rapidpixel
{
/**
 * @brief Field of view point class.
 *
 * @note The class is not thread-safe: an object must not be accessed from
 * several threads at the same time without external synchronization.
 */
class FovPoint
{
public:
    /// Hardware zoom pos.
    int hwZoomPos{0};
    /// Horizontal field of view, degree.
    float xFovDeg{0.0f};
    /// Vertical field of view, degree.
    float yFovDeg{0.0f};

    JSON_READABLE(FovPoint, hwZoomPos, xFovDeg, yFovDeg)

    /**
     * @brief Default constructor.
     */
    FovPoint() = default;

    /**
     * @brief Copy constructor.
     * @param src Source object.
     */
    FovPoint(const FovPoint& src) = default;

    /**
     * @brief Move constructor.
     * @param src Source object.
     */
    FovPoint(FovPoint&& src) = default;

    /**
     * @brief Copy assignment operator.
     * @param src Source object.
     * @return Reference to this object.
     */
    FovPoint& operator= (const FovPoint& src) = default;

    /**
     * @brief Move assignment operator.
     * @param src Source object.
     * @return Reference to this object.
     */
    FovPoint& operator= (FovPoint&& src) = default;
};

/**
 * @brief Lens params class.
 *
 * @note The class is not thread-safe: an object must not be accessed from
 * several threads at the same time without external synchronization.
 */
class LensParams
{
public:
    /// Initialization string. Particular lens controller can have unique init
    /// string format. But it is recommended to use '**;**' symbol to divide
    /// parts of initialization string. Recommended initialization string format
    /// for controllers which uses serial port: "/dev/ttyUSB0;9600;100"
    /// ("/dev/ttyUSB0" - serial port name, "9600" - baudrate, "100" - serial
    /// port read timeout).
    std::string initString{"/dev/ttyUSB0;9600;20"};
    /// Zoom position. Setting a parameter is equivalent to the command
    /// ZOOM_TO_POS. Lens controller should have zoom range from 0 (full wide)
    /// to 65535 (full tele) regardless of the hardware value of the zoom
    /// position. If the minimum and maximum zoom position limits are set by
    /// the user in the lens parameters, the range of the hardware zoom position
    /// must be scaled to the user space 0-65535 range. Parameter value: zoom
    /// position 0-65535. User should be able to set zoom movement speed via
    /// lens parameters.
    int zoomPos{0};
    /// Hardware zoom position. Parameter value depends on implementation and
    /// lens hardware.
    int zoomHwPos{0};
    /// Focus position. Setting a parameter is equivalent to the command
    /// FOCUS_TO_POS. Lens controller should have focus range from 0 (full near)
    /// to 65535 (full far) regardless of the hardware value of the focus
    /// position. If the minimum and maximum focus position limits are set by
    /// the user in the lens parameters, the range of the hardware focus
    /// position must be scaled to the 0-65535 user space range. Parameter
    /// value: focus position 0-65535. User should be able to set focus movement
    /// speed via lens parameters.
    int focusPos{0};
    /// Hardware focus position. Parameter value depends on implementation and
    /// lens hardware.
    int focusHwPos{0};
    /// Iris position. Setting a parameter is equivalent to the command
    /// IRIS_TO_POS. Lens controller should have iris range from 0 (full close)
    /// to 65535 (full far) regardless of the hardware value of the iris
    /// position. If the minimum and maximum iris position limits are set by the
    /// user in the lens parameters, the range of the hardware iris position
    /// must be scaled to the 0-65535 user space range. Parameter value: iris
    /// position 0-65535. User should be able to set iris movement speed via
    /// lens parameters.
    int irisPos{0};
    /// Hardware iris position. Parameter value depends on implementation.
    int irisHwPos{0};
    /// Focus mode. Parameter value depends on implementation but it is
    /// recommended to keep default values: 0 - Manual focus control,
    /// 1 - Auto focus control.
    int focusMode{0};
    /// Filter mode. Parameter value depends on implementation but it is
    /// recommended to keep default values: 0 - Filter on, 1 - Filter off.
    int filterMode{0};
    /// Autofocus ROI top-left corner horizontal position in pixels.
    /// Autofocus ROI is rectangle.
    int afRoiX0{0};
    /// Autofocus ROI top-left corner vertical position in pixels.
    /// Autofocus ROI is rectangle.
    int afRoiY0{0};
    /// Autofocus ROI bottom-right corner horizontal position in pixels.
    /// Autofocus ROI is rectangle.
    int afRoiX1{0};
    /// Autofocus ROI bottom-right corner vertical position in pixels.
    /// Autofocus ROI is rectangle.
    int afRoiY1{0};
    /// Zoom speed. Lens controller should have zoom speed range from 0 to
    /// 100% of max hardware zoom speed (parameter ZOOM_HW_MAX_SPEED). If the
    /// user sets a new parameter value of the ZOOM_HW_SPEED the parameter
    /// ZOOM_SPEED must be updated automatically. Formula for calculating speed:
    /// ZOOM_SPEED = ( ZOOM_HW_SPEED / ZOOM_HW_MAX_SPEED) * 100.
    int zoomSpeed{50};
    /// Zoom hardware speed. Value depends on implementation and lens hardware.
    /// The value of the parameters must be <= ZOOM_HW_MAX_SPEED parameter.
    /// If the user sets a new parameter value of the ZOOM_SPEED parameter
    /// the parameter ZOOM_HW_SPEED must be updated automatically. Formula for
    /// calculating hardware speed:
    /// ZOOM_HW_SPEED = ( ZOOM_SPEED / 100 ) * ZOOM_HW_MAX_SPEED.
    int zoomHwSpeed{50};
    /// Maximum zoom hardware speed. Value depends on implementation. If user
    /// sets new ZOOM_HW_MAX_SPEED value the parameters ZOOM_SPEED must be
    /// updated automatically. If new value of ZOOM_HW_MAX_SPEED parameter will
    /// be less than ZOOM_HW_SPEED the parameter ZOOM_HW_SPEED must be reduced
    /// automatically.
    int zoomHwMaxSpeed{50};
    /// Focus speed. Lens controller should have focus speed range from 0 to
    /// 100% of max hardware focus speed (parameter FOCUS_HW_MAX_SPEED). If the
    /// user sets a new parameter value of the FOCUS_HW_SPEED the parameter
    /// FOCUS_SPEED must be updated automatically. Formula for calculating
    /// speed: FOCUS_SPEED = ( FOCUS_HW_SPEED / FOCUS_HW_MAX_SPEED) * 100.
    int focusSpeed{50};
    /// Focus hardware speed. Value depends on on implementation and lens
    /// hardware. The value of the parameters must be <= FOCUS_HW_MAX_SPEED
    /// parameter. If the user sets a new parameter value of the FOCUS_SPEED
    /// parameter the parameter FOCUS_HW_SPEED must be updated automatically.
    /// Formula for calculating hardware speed:
    /// FOCUS_HW_SPEED = ( FOCUS_SPEED / 100 ) * FOCUS_HW_MAX_SPEED.
    int focusHwSpeed{50};
    /// Maximum focus hardware speed. Value depends on implementation. If user
    /// sets new FOCUS_HW_MAX_SPEED value the parameters FOCUS_SPEED and
    /// FOCUS_HW_SPEED must be updated by lens controller automatically.
    /// If new value of FOCUS_HW_MAX_SPEED parameter will be less than
    /// FOCUS_HW_SPEED the parameter FOCUS_HW_SPEED must be reduced
    /// automatically.
    int focusHwMaxSpeed{50};
    /// Iris speed. Lens controller should have iris speed range from 0 to 100%
    /// of max hardware iris speed (parameter IRIS_HW_MAX_SPEED). If the user
    /// sets a new parameter value of the IRIS_HW_SPEED the parameter IRIS_SPEED
    /// must be updated automatically. Formula for calculating speed:
    /// IRIS_SPEED = ( IRIS_HW_SPEED / IRIS_HW_MAX_SPEED) * 100.
    int irisSpeed{50};
    /// Iris hardware speed. Value depends on implementation and lens hardware.
    /// The value of the parameters must be <= IRIS_HW_MAX_SPEED parameter.
    /// If the user sets a new parameter value of the IRIS_SPEED parameter the
    /// parameter IRIS_HW_SPEED must be updated automatically. Formula for
    /// calculating hardware speed:
    /// IRIS_HW_SPEED = ( IRIS_SPEED / 100 ) * IRIS_HW_MAX_SPEED.
    int irisHwSpeed{50};
    /// Maximum iris hardware speed. Value depends on implementation. If user
    /// sets new IRIS_HW_MAX_SPEED value the parameters IRIS_SPEED and
    /// IRIS_HW_SPEED must be updated automatically. If new value of
    /// IRIS_HW_MAX_SPEED parameter will be less than IRIS_HW_SPEED the
    /// parameter IRIS_HW_SPEED must be reduced automatically.
    int irisHwMaxSpeed{50};
    /// Zoom hardware tele limit. Value depends on implementation and lens
    /// hardware. Lens controller should control zoom position. Lens controller
    /// should stop zoom moving if hardware zoom position will be out of limits.
    int zoomHwTeleLimit{65535};
    /// Zoom hardware wide limit. Value depends on implementation and lens
    /// hardware. Lens controller should control zoom position. Lens controller
    /// should stop zoom moving if hardware zoom position will be out of limits.
    int zoomHwWideLimit{0};
    /// Focus hardware far limit. Value depends on on implementation and lens
    /// hardware. Lens controller should control focus position. Lens controller
    /// should stop focus moving if hardware focus position will be out of
    /// limits.
    int focusHwFarLimit{65535};
    /// Focus hardware near limit. Value depends on implementation and lens
    /// hardware. Lens controller should control focus position. Lens controller
    /// should stop focus moving if hardware focus position will be out of
    /// limits.
    int focusHwNearLimit{0};
    /// Iris hardware open limit. Value depends on implementation and lens
    /// hardware. Lens controller should control iris position. Lens controller
    /// should stop iris moving if hardware iris position will be out of limits.
    int irisHwOpenLimit{65535};
    /// Iris hardware close limit. Value depends on implementation and lens
    /// hardware. Lens controller should control iris position. Lens controller
    /// should stop iris moving if hardware iris position will be out of limits.
    int irisHwCloseLimit{0};
    /// Focus factor if it was calculated. If not calculated must be -1.
    /// Value depends on particular lens controller.
    float focusFactor{0.0f};
    /// Lens connection status. Connection status shows if the lens controller
    /// has data exchange with lens equipment. For example, if lens has serial
    /// port lens controller connects to serial port (opens serial port file
    /// in OS) but lens can be not active (no power). In this case connection
    /// status shows that lens controller doesn't have data exchange with lens
    /// equipment. If lens controller has data exchange with lens equipment
    /// the value is TRUE. If lens controller not initialize the connection
    /// status always FALSE. Value: false - not connected. true - connected.
    bool isConnected{false};
    /// Focus hardware speed in autofocus mode. Value depends on implementation
    /// and lens hardware.
    int afHwSpeed{50};
    /// Threshold for changes of focus factor to start refocus. Value:
    /// 0% - no check, 100% - changing x2.
    float focusFactorThreshold{0.0f};
    /// Timeout for automatic refocus in seconds. Value:
    /// 0 - no automatic refocus, 100000 - maximum value.
    int refocusTimeoutSec{0};
    /// Flag about active autofocus algorithm. Value: 0 - autofocus not working,
    /// 1 - working.
    bool afIsActive{false};
    /// Iris mode. Value depends on implementation but it is recommended to keep
    /// default values: 0 - manual iris control, 1 - auto iris control.
    int irisMode{0};
    /// ROI width (pixels) for autofocus algorithm when lens controller detects
    /// ROI position automatically. Value: from 8 to (video frame width -
    /// AUTO_AF_ROI_BORDER * 2).
    int autoAfRoiWidth{150};
    /// ROI height (pixels) for autofocus algorithm when lens controller detects
    /// ROI position automatically. Value: from 8 to (video frame height -
    /// AUTO_AF_ROI_BORDER * 2).
    int autoAfRoiHeight{150};
    /// Video frame border size (along vertical and horizontal axes).
    /// Value: border size from 0 to video
    /// frame min(video frame width/height) / 2.
    int autoAfRoiBorder{100};
    /// AF ROI mode (write/read). Value: 0 - Manual position, 1 - Auto position.
    int afRoiMode{0};
    /// Lens extender mode. Value depends on implementation but it is
    /// recommended to keep default values: 0 - no extender, 1 - x2 extender.
    int extenderMode{0};
    /// Lens stabilization mode. Value depends on implementation but it is
    /// recommended to keep default values: 0 - no stabilization,
    /// 1 - stabilization.
    int stabiliserMode{0};
    /// Autofocus range. Value depends on implementation.
    int afRange{0};
    /// Current horizontal Field of view, degree. Field of view calculated by
    /// lens controller according to initial params or by reading directly from
    /// lens hardware.
    float xFovDeg{1.0f};
    /// Current vertical Field of view, degree. Field of view calculated by lens
    /// controller according to initial params or by reading directly from lens
    /// hardware.
    float yFovDeg{1.0f};
    /// Logging mode. Values: 0 - Disable, 1 - Only file, 2 - Only terminal,
    /// 3 - File and terminal.
    int logMode{0};
    /// Lens temperature, degree (read only).
    float temperature{0.0f};
    /// Lens controller initialization status. Open status shows if the lens
    /// controller initialized or not but doesn't show if lens controller has
    /// communication with lens equipment. For example, if lens has serial port
    /// lens controller connects to serial port (opens serial port file in OS)
    /// but lens can be not active (no power). In this case open status just
    /// shows that lens controller has opened serial port.
    /// Values: false - not open (not initialized), true - open (initialized).
    bool isOpen{false};
    /// Lens type. Value depends on implementation. Type allows to lens
    /// initialize necessary parameters for particular lens hardware.
    int type{0};
    /// Lens custom parameter. Value depends on particular lens controller.
    /// Custom parameters used when particular lens equipment has specific
    /// unusual parameter.
    float custom1{0.0f};
    /// Lens custom parameter. Value depends on particular lens controller.
    /// Custom parameters used when particular lens equipment has specific
    /// unusual parameter.
    float custom2{0.0f};
    /// Lens custom parameter. Value depends on particular lens controller.
    /// Custom parameters used when particular lens equipment has specific
    /// unusual parameter.
    float custom3{0.0f};
    /// List of points to calculate field of view. Lens controller should
    /// calculate FOV table according to given list of points using
    /// approximation.
    std::vector<FovPoint> fovPoints{std::vector<FovPoint>()};

    JSON_READABLE(LensParams, initString, focusMode, filterMode,
                  afRoiX0, afRoiY0, afRoiX1, afRoiY1, zoomHwMaxSpeed,
                  focusHwMaxSpeed, irisHwMaxSpeed, zoomHwTeleLimit,
                  zoomHwWideLimit, focusHwFarLimit, focusHwNearLimit,
                  irisHwOpenLimit, irisHwCloseLimit, afHwSpeed,
                  focusFactorThreshold, refocusTimeoutSec, irisMode,
                  autoAfRoiWidth, autoAfRoiHeight, autoAfRoiBorder,
                  afRoiMode, extenderMode, stabiliserMode, afRange,
                  logMode, type, custom1, custom2, custom3, fovPoints)

    /**
     * @brief Default constructor.
     */
    LensParams() = default;

    /**
     * @brief Copy constructor.
     * @param src Source object.
     */
    LensParams(const LensParams& src) = default;

    /**
     * @brief Move constructor.
     * @param src Source object.
     */
    LensParams(LensParams&& src) = default;

    /**
     * @brief Copy assignment operator.
     * @param src Source object.
     * @return Reference to this object.
     */
    LensParams& operator= (const LensParams& src) = default;

    /**
     * @brief Move assignment operator.
     * @param src Source object.
     * @return Reference to this object.
     */
    LensParams& operator= (LensParams&& src) = default;

    /**
     * @brief Encode (serialize) params.
     *
     * The method doesn't encode initString and fovPoints. The encoded data
     * consists of the header (data type, version Major and Minor, params mask
     * of 7 bytes: one bit for each field of LensParamsMask) and the values of
     * the selected params in the order of the LensParamsMask fields. Values of
     * int and float fields use 4 bytes in the byte order of the host, values
     * of bool fields use 1 byte.
     *
     * @param data Pointer to data buffer. Must not be nullptr and must be
     * valid for bufferSize bytes.
     * @param bufferSize Size of the data buffer, bytes. Must be >= 201 (the
     * size of the data with all params encoded).
     * @param size Size of the encoded data, bytes. Set to 0 if the params
     * are not encoded.
     * @param mask Pointer to params mask. If nullptr all params are encoded.
     * @return TRUE if params encoded or FALSE if not (data is nullptr or
     * bufferSize < 201).
     */
    bool encode(uint8_t* data, int bufferSize, int& size,
                LensParamsMask* mask = nullptr);

    /**
     * @brief Decode (deserialize) params encoded by encode(...) method.
     *
     * The method doesn't decode initString and fovPoints: initString is set
     * to empty string and fovPoints is cleared. The method checks data type,
     * version (Major and Minor) and params mask, and checks that each encoded
     * value is inside the data before reading it. Params which are not
     * encoded are set to 0 (FALSE for bool params). Bytes after the last
     * encoded value are ignored. Values of params are not checked against any
     * range: the lens controller must validate them before use.
     *
     * @param data Pointer to encoded data. Must not be nullptr and must be
     * valid for dataSize bytes.
     * @param dataSize Size of the encoded data, bytes.
     * @return TRUE if params decoded or FALSE if not. If FALSE is returned
     * the object is not changed.
     */
    bool decode(uint8_t* data, int dataSize);
};
}

Table 4 - LensParams class fields description is equivalent to LensParam enum description.

Field type Description
initString string Initialization string contains full serial port name, baudrate, timeout separated by “;”. Example: “/dev/ttyUSB0;19200;50”. Baudrate and timeout optional params and will be set by default in the library.
zoomPos int Zoom position 0 (full wide) - 65535 (full tele).
zoomHwPos int Hardware zoom position 0 (full wide) - 64000 (full tele) by default.
focusPos int Focus position 0 (full near) - 65535 (full far).
focusHwPos int Hardware focus position 0 (full near) - 64000 (full far) by default.
irisPos int Iris position 0 (full close) - 65535 (full open).
irisHwPos int Hardware iris position 0 (full close) - 32000 (full open) by default.
focusMode int Focus mode:
0 - Manual focus control.
1 - Push auto focus mode.
2 - Continuous auto focus mode.
filterMode int Filter mode (number of the filter). Value: 0 - 255.
afRoiX0 int Autofocus ROI top-left corner horizontal position in pixels. Autofocus ROI is rectangle.
afRoiY0 int Autofocus ROI top-left corner vertical position in pixels. Autofocus ROI is rectangle.
afRoiX1 int Autofocus ROI bottom-right corner horizontal position in pixels. Autofocus ROI is rectangle.
afRoiY1 int Autofocus ROI bottom-right corner vertical position in pixels. Autofocus ROI is rectangle.
zoomSpeed int Zoom speed. Zoom speed range from 0 to 100 which means 0-100% of max hardware zoom speed.
zoomHwSpeed int Zoom hardware speed. Zoom hardware speed range from 0 to 7.
zoomHwMaxSpeed int Maximum zoom hardware speed. Default value 7.
focusSpeed int Focus speed. Focus speed range from 0 to 100 which means 0-100% of max hardware focus speed.
focusHwSpeed int Focus hardware speed. Focus hardware speed range from 0 to 7.
focusHwMaxSpeed int Maximum focus hardware speed. Default value 7.
irisSpeed int Not supported by Rpl class.
irisHwSpeed int Not supported by Rpl class.
irisHwMaxSpeed int Not supported by Rpl class.
zoomHwTeleLimit int Zoom hardware tele limit. Default value 64000.
zoomHwWideLimit int Zoom hardware wide limit. Default value 0.
focusHwFarLimit int Focus hardware far limit. Default value 64000.
focusHwNearLimit int Focus hardware near limit. Default value 0.
irisHwOpenLimit int Iris hardware open limit. Default value 32000.
irisHwCloseLimit int Iris hardware close limit. Default value 0.
focusFactor float Focus factor if it was calculated. If not calculated must be -1.
isConnected bool Lens connection status. Connection status shows if the lens controller has data exchange with lens equipment. Values:
0 - no response from lens.
1 - connected.
afHwSpeed int Focus hardware speed in autofocus mode. Default value 2.
focusFactorThreshold float Threshold for changes of focus factor to start refocus. Values: 0% - no check, 100% - changing x2.
refocusTimeoutSec int Timeout for automatic refocus in seconds. Value: 0 - no automatic refocus, 1000 - maximum value.
afIsActive bool Flag about active autofocus algorithm. Value: 0 - autofocus not working, 1 - working.
irisMode int Not supported by Rpl class.
autoAfRoiWidth int ROI width (pixels) for autofocus algorithm when lens controller detects ROI position automatically. Value: from 8 to (video frame width - AUTO_AF_ROI_BORDER * 2).
autoAfRoiHeight int ROI height (pixels) for autofocus algorithm when lens controller detects ROI position automatically. Value: from 8 to (video frame height - AUTO_AF_ROI_BORDER * 2).
autoAfRoiBorder int Video frame border size (along vertical and horizontal axes). Value: 0 - 2048 (the value is checked by the autofocus engine). The ROI position is detected only if the border is not more than a quarter of the video frame width and height.
afRoiMode int Auto focus ROI mode. Values:
0 - Manual position.
1 - Auto position. The controller will detect “optimal” auto focus ROI position.
extenderMode int Not supported by Rpl class.
stabiliserMode int Not supported by Rpl class.
afRange int Not supported by Rpl class.
xFovDeg float Not supported by Rpl class.
yFovDeg float Not supported by Rpl class.
logMode int Logging mode. Values:
0 - Disable.
1 - Only terminal.
2 - Only file.
3 - File and terminal.
temperature float Lens temperature, degree.
isOpen bool Lens controller initialization status. Open status shows if the lens controller initialized or not but doesn’t show if lens controller has communication with lens equipment. Values: 0 - not open (not initialized), 1 - open (initialized).
type int Not supported by Rpl class.
custom1 float Percent of central ROI for AF Engine. Value: 1-100.
custom2 float Time adjustment for AF Engine, ms.
custom3 float Not supported by Rpl class.
fovPoints FovPoint List of points to calculate field of view. Lens controller should calculate FOV table according to given list of points using approximation. Not supported by Rpl class. Each point includes (FovPoint class):
- hwZoomPos - hardware zoom position.
- xFovDeg - horizontal FOV, degree for hwZoomPos.
- yFovDeg - vertical FOV, degree for hwZoomPos.

Note: LensParams class fields listed in above reflect params set/get by methods setParam(…) and getParam(…).

Serialize lens params

LensParams class provides method encode(…) to serialize lens params (fields of LensParams class, see Table 4). Serialization of lens params necessary in case when you need to send lens params via communication channels. Method doesn’t encode initString string field and fovPoints. Method provides options to exclude particular parameters from serialization. To do this method inserts binary mask (7 bytes) where each bit represents particular parameter and decode(…) method recognizes it. Method declaration:

bool encode(uint8_t* data, int bufferSize, int& size, LensParamsMask* mask = nullptr);
Parameter Value
data Pointer to data buffer. Must not be nullptr.
bufferSize Data buffer size. Buffer size must be >= 201 bytes (the size of data with all parameters) regardless of the mask.
size Size of encoded data. Set to 0 if the parameters are not encoded.
mask Parameters mask - pointer to LensParamsMask structure. LensParamsMask (declared in Lens.h file) determines flags for each field (parameter) declared in LensParams class. If the user wants to exclude any parameters from serialization, he can put a pointer to the mask. If the user wants to exclude a particular parameter from serialization, he should set the corresponding flag of the LensParamsMask structure to false. If mask is nullptr all parameters are encoded.

Returns: TRUE if the parameters were encoded or FALSE if not (data is nullptr or bufferSize is less than 201). If the method returns FALSE size is set to 0 and nothing is written to the buffer.

The encoded data consists of: data type (1 byte, 0x02), version Major and Minor (2 bytes), mask (7 bytes) and values of the selected parameters. The n-th field of LensParamsMask uses the bit (0x80 » (n % 8)) of the mask byte n / 8 (fields are numbered from 0 in the order of the structure declaration). Values follow the mask in the order of the LensParamsMask fields. Values of int and float fields use 4 bytes in the byte order of the host (see Portability section), values of bool fields use 1 byte (0 or 1). The size of encoded data is from 10 bytes (no parameters) to 201 bytes (all parameters).

LensParamsMask structure declaration:

/**
 * @brief Lens params mask structure.
 *
 * Each flag enables serialization of the LensParams field with the same
 * name (see LensParams::encode(...)).
 */
typedef struct LensParamsMask
{
    bool zoomPos{true};  ///< Serialize zoomPos.
    bool zoomHwPos{true};  ///< Serialize zoomHwPos.
    bool focusPos{true};  ///< Serialize focusPos.
    bool focusHwPos{true};  ///< Serialize focusHwPos.
    bool irisPos{true};  ///< Serialize irisPos.
    bool irisHwPos{true};  ///< Serialize irisHwPos.
    bool focusMode{true};  ///< Serialize focusMode.
    bool filterMode{true};  ///< Serialize filterMode.
    bool afRoiX0{true};  ///< Serialize afRoiX0.
    bool afRoiY0{true};  ///< Serialize afRoiY0.
    bool afRoiX1{true};  ///< Serialize afRoiX1.
    bool afRoiY1{true};  ///< Serialize afRoiY1.
    bool zoomSpeed{true};  ///< Serialize zoomSpeed.
    bool zoomHwSpeed{true};  ///< Serialize zoomHwSpeed.
    bool zoomHwMaxSpeed{true};  ///< Serialize zoomHwMaxSpeed.
    bool focusSpeed{true};  ///< Serialize focusSpeed.
    bool focusHwSpeed{true};  ///< Serialize focusHwSpeed.
    bool focusHwMaxSpeed{true};  ///< Serialize focusHwMaxSpeed.
    bool irisSpeed{true};  ///< Serialize irisSpeed.
    bool irisHwSpeed{true};  ///< Serialize irisHwSpeed.
    bool irisHwMaxSpeed{true};  ///< Serialize irisHwMaxSpeed.
    bool zoomHwTeleLimit{true};  ///< Serialize zoomHwTeleLimit.
    bool zoomHwWideLimit{true};  ///< Serialize zoomHwWideLimit.
    bool focusHwFarLimit{true};  ///< Serialize focusHwFarLimit.
    bool focusHwNearLimit{true};  ///< Serialize focusHwNearLimit.
    bool irisHwOpenLimit{true};  ///< Serialize irisHwOpenLimit.
    bool irisHwCloseLimit{true};  ///< Serialize irisHwCloseLimit.
    bool focusFactor{true};  ///< Serialize focusFactor.
    bool isConnected{true};  ///< Serialize isConnected.
    bool afHwSpeed{true};  ///< Serialize afHwSpeed.
    bool focusFactorThreshold{true};  ///< Serialize focusFactorThreshold.
    bool refocusTimeoutSec{true};  ///< Serialize refocusTimeoutSec.
    bool afIsActive{true};  ///< Serialize afIsActive.
    bool irisMode{true};  ///< Serialize irisMode.
    bool autoAfRoiWidth{true};  ///< Serialize autoAfRoiWidth.
    bool autoAfRoiHeight{true};  ///< Serialize autoAfRoiHeight.
    bool autoAfRoiBorder{true};  ///< Serialize autoAfRoiBorder.
    bool afRoiMode{true};  ///< Serialize afRoiMode.
    bool extenderMode{true};  ///< Serialize extenderMode.
    bool stabiliserMode{true};  ///< Serialize stabiliserMode.
    bool afRange{true};  ///< Serialize afRange.
    bool xFovDeg{true};  ///< Serialize xFovDeg.
    bool yFovDeg{true};  ///< Serialize yFovDeg.
    bool logMode{true};  ///< Serialize logMode.
    bool temperature{true};  ///< Serialize temperature.
    bool isOpen{true};  ///< Serialize isOpen.
    bool type{true};  ///< Serialize type.
    bool custom1{true};  ///< Serialize custom1.
    bool custom2{true};  ///< Serialize custom2.
    bool custom3{true};  ///< Serialize custom3.
} LensParamsMask;

Example without parameters mask:

// Encode data.
rapidpixel::LensParams in;
in.logMode = 3;
uint8_t data[1024];
int size = 0;
if (!in.encode(data, 1024, size))
{
    std::cout << "Can't encode data" << std::endl;
    return false;
}
std::cout << "Encoded data size: " << size << " bytes" << std::endl;

Example with parameters mask:

// Prepare params.
rapidpixel::LensParams in;
in.logMode = 3;

// Prepare mask.
rapidpixel::LensParamsMask mask;
mask.logMode = false; // Exclude logMode. Others by default.

// Encode.
uint8_t data[1024];
int size = 0;
if (!in.encode(data, 1024, size, &mask))
{
    std::cout << "Can't encode data" << std::endl;
    return false;
}
std::cout << "Encoded data size: " << size << " bytes" << std::endl;

Deserialize lens params

LensParams class provides method decode(…) to deserialize lens params (fields of LensParams class, see Table 4). Deserialization of lens params necessary in case when you need to receive lens params via communication channels. Method automatically recognizes which parameters were serialized by encode(…) method. Method doesn’t decode fields: initString and fovPoints (after decoding initString is empty and fovPoints is empty). Parameters which were not serialized are set to 0 (false for bool parameters). Method checks that the data has all values selected by the mask before it changes the object. Bytes after the last value are ignored. Values of the parameters are not checked against any range: lens controller must validate them before use. Method declaration:

bool decode(uint8_t* data, int dataSize);
Parameter Value
data Pointer to data buffer. Must not be nullptr.
dataSize Size of data, bytes.

Returns: TRUE if data decoded (deserialized) or FALSE if not: data is nullptr, dataSize is less than 10 (size of the header), data type or version (Major and Minor) is wrong, the mask has bits of unknown fields (the last 6 bits of the last mask byte must be 0) or the data doesn’t have all values selected by the mask. If the method returns FALSE the object is not changed.

Example:

// Encode data.
rapidpixel::LensParams in;
uint8_t data[1024];
int size = 0;
if (!in.encode(data, 1024, size))
{
    std::cout << "Can't encode data" << std::endl;
    return false;
}
std::cout << "Encoded data size: " << size << " bytes" << std::endl;

// Decode data.
rapidpixel::LensParams out;
if (!out.decode(data, size))
{
    std::cout << "Can't decode data" << std::endl;
    return false;
}

Read params from JSON file and write to JSON file

Lens interface class library depends on ConfigReader library which provides method to read params from JSON file and to write params to JSON file. Example of writing and reading params to JSON file:

// Prepare params.
rapidpixel::LensParams in;
for (int i = 0; i < 5; ++i)
{
    rapidpixel::FovPoint pt;
    pt.hwZoomPos = 100 * i;
    pt.xFovDeg = 10.0f + static_cast<float>(i);
    pt.yFovDeg = 5.0f + static_cast<float>(i);
    in.fovPoints.push_back(pt);
}

// Write params to file.
rapidpixel::ConfigReader inConfig;
if (!inConfig.set(in, "lensParams") ||
    !inConfig.writeToFile("TestLensParams.json"))
{
    std::cout << "Can't write config file" << std::endl;
    return false;
}

// Read params from file.
rapidpixel::ConfigReader outConfig;
rapidpixel::LensParams out;
if (!outConfig.readFromFile("TestLensParams.json") ||
    !outConfig.get(out, "lensParams"))
{
    std::cout << "Can't read params from file" << std::endl;
    return false;
}

TestLensParams.json will look like:

{
    "lensParams": {
        "initString": "/dev/ttyUSB0;9600;20",
        "focusMode": 0,
        "filterMode": 0,
        "afRoiX0": 0,
        "afRoiY0": 0,
        "afRoiX1": 0,
        "afRoiY1": 0,
        "zoomHwMaxSpeed": 50,
        "focusHwMaxSpeed": 50,
        "irisHwMaxSpeed": 50,
        "zoomHwTeleLimit": 65535,
        "zoomHwWideLimit": 0,
        "focusHwFarLimit": 65535,
        "focusHwNearLimit": 0,
        "irisHwOpenLimit": 65535,
        "irisHwCloseLimit": 0,
        "afHwSpeed": 50,
        "focusFactorThreshold": 0.0,
        "refocusTimeoutSec": 0,
        "irisMode": 0,
        "autoAfRoiWidth": 150,
        "autoAfRoiHeight": 150,
        "autoAfRoiBorder": 100,
        "afRoiMode": 0,
        "extenderMode": 0,
        "stabiliserMode": 0,
        "afRange": 0,
        "logMode": 0,
        "type": 0,
        "custom1": 0.0,
        "custom2": 0.0,
        "custom3": 0.0,
        "fovPoints": [
            {
                "hwZoomPos": 0,
                "xFovDeg": 10.0,
                "yFovDeg": 5.0
            },
            {
                "hwZoomPos": 100,
                "xFovDeg": 11.0,
                "yFovDeg": 6.0
            },
            {
                "hwZoomPos": 200,
                "xFovDeg": 12.0,
                "yFovDeg": 7.0
            },
            {
                "hwZoomPos": 300,
                "xFovDeg": 13.0,
                "yFovDeg": 8.0
            },
            {
                "hwZoomPos": 400,
                "xFovDeg": 14.0,
                "yFovDeg": 9.0
            }
        ]
    }
}

Build and connect to your project

Build stand alone

The repository doesn’t contain sub-repositories. The libraries Rpl depends on (Frame, ConfigReader, AFEngine, SerialPort, Lens and Logger) must be cloned into the same folder as Rpl. The folder structure must be:

<work folder>
    Rpl
    Frame
    ConfigReader
    AFEngine
    SerialPort
    Lens
    Logger

Typical commands to build the library, the test application and the example (use the URLs of the repositories provided to you):

git clone <Rpl repository URL>
git clone <Frame repository URL>
git clone <ConfigReader repository URL>
git clone <AFEngine repository URL>
git clone <SerialPort repository URL>
git clone <Lens repository URL>
git clone <Logger repository URL>
cd Rpl
mkdir build
cd build
cmake ..
make

On Windows use cmake --build . --config Release instead of make. If Rpl is the top-level CMake project, the main CMakeLists.txt file adds the folders ../Frame, ../ConfigReader, ../AFEngine, ../SerialPort, ../Lens and ../Logger (in this order) before the library itself. If a folder doesn’t exist CMake stops with an error.

The RpLensParser library is a part of the repository (folder src/parser, see src/parser/README.md) and is not cloned separately: the main CMakeLists.txt file of Rpl adds the folder src/parser before the library in every build (stand alone and when Rpl is included in another project). The test application of the parser (folder src/parser/test) is not built.

CMake options

Table 5 - CMake options of the repository. In the options below ${PARENT} is the prefix defined by the top-level project (empty if Rpl is the top-level project).

Option Default Description
${PARENT}_RPL ON Build the library.
${PARENT}_RPL_TEST ON (stand alone), OFF (included in other project) Build the test application.
${PARENT}_RPL_EXAMPLE ON (stand alone), OFF (included in other project) Build the example.
${PARENT}_SUBMODULE_CACHE_OVERWRITE ON Forced rewriting of the options above in the CMake cache. The top-level project sets it to OFF when it includes Rpl as a sub-repository.
CMAKE_BUILD_TYPE Release (if not specified) Build type.

Connect to your project

If you want to connect Rpl library to your CMake project as source code you can make follow. For example, if your repository has structure:

CMakeLists.txt
src
    CMakeLists.txt
    yourLib.h
    yourLib.cpp

Create folder 3rdparty in your repository and clone (or copy) the repositories of Frame, ConfigReader, AFEngine, SerialPort, Lens, Logger and Rpl there. Structure of your repository with the libraries:

CMakeLists.txt
src
    CMakeLists.txt
    yourLib.h
    yourLib.cpp
3rdparty
    Frame
    ConfigReader
    AFEngine
    SerialPort
    Lens
    Logger
    Rpl

When Rpl is included in another project it doesn’t add the other libraries it depends on: your project must add them by itself, in the order of their mutual dependencies (Frame and ConfigReader before the libraries which use them), before or after Rpl. If they are not added the compiler stops with the error AFEngine.h: No such file or directory. Create CMakeLists.txt file in 3rdparty folder. CMakeLists.txt should contain:

cmake_minimum_required(VERSION 3.13)

################################################################################
## 3RD-PARTY
## dependencies for the project
################################################################################
project(3rdparty LANGUAGES CXX)

################################################################################
## SETTINGS
## basic 3rd-party settings before use
################################################################################
# To inherit the top-level architecture when the project is used as a submodule.
SET(PARENT ${PARENT}_YOUR_PROJECT_3RDPARTY)
# Disable self-overwriting of parameters inside included subdirectories.
SET(${PARENT}_SUBMODULE_CACHE_OVERWRITE OFF CACHE BOOL "" FORCE)

################################################################################
## CONFIGURATION
## 3rd-party submodules configuration
################################################################################
SET(${PARENT}_SUBMODULE_FRAME                           ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_FRAME)
    SET(${PARENT}_FRAME                                 ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_FRAME_TEST                            OFF CACHE BOOL "" FORCE)
endif()

SET(${PARENT}_SUBMODULE_CONFIG_READER                   ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_CONFIG_READER)
    SET(${PARENT}_CONFIG_READER                         ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_CONFIG_READER_TESTS                   OFF CACHE BOOL "" FORCE)
    SET(${PARENT}_CONFIG_READER_EXAMPLES                OFF CACHE BOOL "" FORCE)
endif()

SET(${PARENT}_SUBMODULE_AF_ENGINE                       ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_AF_ENGINE)
    SET(${PARENT}_AF_ENGINE                             ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_AF_ENGINE_TEST                        OFF CACHE BOOL "" FORCE)
endif()

SET(${PARENT}_SUBMODULE_SERIAL_PORT                     ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_SERIAL_PORT)
    SET(${PARENT}_SERIAL_PORT                           ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_SERIAL_PORT_EXAMPLES                  OFF CACHE BOOL "" FORCE)
endif()

SET(${PARENT}_SUBMODULE_LENS                            ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_LENS)
    SET(${PARENT}_LENS                                  ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_LENS_TEST                             OFF CACHE BOOL "" FORCE)
    SET(${PARENT}_LENS_EXAMPLE                          OFF CACHE BOOL "" FORCE)
endif()

SET(${PARENT}_SUBMODULE_LOGGER                          ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_LOGGER)
    SET(${PARENT}_LOGGER                                ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_LOGGER_EXAMPLE                        OFF CACHE BOOL "" FORCE)
endif()

SET(${PARENT}_SUBMODULE_RPL                             ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_RPL)
    SET(${PARENT}_RPL                                   ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_RPL_TEST                              OFF CACHE BOOL "" FORCE)
    SET(${PARENT}_RPL_EXAMPLE                           OFF CACHE BOOL "" FORCE)
endif()

################################################################################
## INCLUDING SUBDIRECTORIES
## Adding subdirectories according to the 3rd-party configuration
################################################################################
if (${PARENT}_SUBMODULE_FRAME)
    add_subdirectory(Frame)
endif()

if (${PARENT}_SUBMODULE_CONFIG_READER)
    add_subdirectory(ConfigReader)
endif()

if (${PARENT}_SUBMODULE_AF_ENGINE)
    add_subdirectory(AFEngine)
endif()

if (${PARENT}_SUBMODULE_SERIAL_PORT)
    add_subdirectory(SerialPort)
endif()

if (${PARENT}_SUBMODULE_LENS)
    add_subdirectory(Lens)
endif()

if (${PARENT}_SUBMODULE_LOGGER)
    add_subdirectory(Logger)
endif()

if (${PARENT}_SUBMODULE_RPL)
    add_subdirectory(Rpl)
endif()

File 3rdparty/CMakeLists.txt adds the folders of the libraries and Rpl to your project and excludes test applications and examples from compiling. Next, you need to include the ‘3rdparty’ folder in the main CMakeLists.txt file of your repository. Add the following string at the end of your main CMakeLists.txt:

add_subdirectory(3rdparty)

Next, you have to include Rpl library in your src/CMakeLists.txt file:

target_link_libraries(${PROJECT_NAME} Rpl)

Done!

Portability

The library doesn’t use SIMD instructions or CPU specific code. Commands for the lens are built by the RpLensParser library byte by byte (16 bit values of the lens protocol are little-endian), so the exchange with the lens doesn’t depend on the byte order of the host. Encoded commands and params (Lens::encodeCommand(…), Lens::encodeSetParamCommand(…) and LensParams::encode(…)) store int and float values as raw 4 bytes in the byte order of the host: the data given to decodeAndExecuteCommand(…) must be encoded on a host with the same byte order. The library was built and tested only on little-endian CPUs (x86-64 and AArch64).

The library, the example and the test application were built without warnings and the library was run with MSVC 2022 (x86-64), GCC 12 and 13 (x86-64), Clang 15 and 18 (x86-64) and with the GCC 13 cross compiler for AArch64 (run under emulation). The Clang 15 and 18 cross compilers for AArch64 were used to build only.

Simple example

A simple application shows how to use the Rpl library. The application opens the lens (the serial port name can be given as the first argument), waits for the first response of the lens, sets the zoom speed, moves zoom to tele and shows the zoom position. The source code is in the file example/main.cpp.

#include <chrono>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include "Lens.h"
#include "Rpl.h"



namespace
{
/// Default serial port of the lens.
const char* const DEFAULT_PORT{"/dev/ttyUSB0"};
/// Time to wait for the lens to respond, milliseconds.
constexpr int CONNECTION_TIMEOUT_MSEC{5000};
/// Period to check the connection status, milliseconds.
constexpr int CONNECTION_CHECK_PERIOD_MSEC{100};
/// Number of the zoom position prints and the period between them.
constexpr int PRINT_COUNT{50};
constexpr int PRINT_PERIOD_MSEC{100};
/// Zoom speed, percents.
constexpr float ZOOM_SPEED{10.0f};
/// Zoom position: full tele.
constexpr float ZOOM_POSITION_TELE{65535.0f};
}



// Entry point. The serial port name can be given as the first argument.
int main(int argc, char* argv[])
{
    // Init lens controller. The lens is used through the Lens interface.
    std::unique_ptr<rapidpixel::Lens> lens(new rapidpixel::Rpl());
    const std::string initString = argc > 1 ? argv[1] : DEFAULT_PORT;
    if (!lens->openLens(initString))
    {
        std::cout << "ERROR: Can't open lens " << initString << std::endl;
        return 1;
    }

    // Wait for the first response of the lens (the number of checks is
    // limited).
    for (int i = 0; i < CONNECTION_TIMEOUT_MSEC / CONNECTION_CHECK_PERIOD_MSEC
         && !lens->isLensConnected(); ++i)
    {
        std::this_thread::sleep_for(
                    std::chrono::milliseconds(CONNECTION_CHECK_PERIOD_MSEC));
    }
    if (!lens->isLensConnected())
    {
        std::cout << "ERROR: The lens doesn't respond" << std::endl;
        return 1;
    }

    // Get lens Zoom position.
    std::cout << "Zoom pos: " <<
                 lens->getParam(rapidpixel::LensParam::ZOOM_POS) << std::endl;

    // Set Zoom speed to 10%.
    if (!lens->setParam(rapidpixel::LensParam::ZOOM_SPEED, ZOOM_SPEED))
    {
        std::cout << "ERROR: Can't set zoom speed" << std::endl;
        return 1;
    }

    // Go to zoom position 65535 (Full tele).
    if (!lens->executeCommand(rapidpixel::LensCommand::ZOOM_TO_POS,
                              ZOOM_POSITION_TELE))
    {
        std::cout << "ERROR: Can't move zoom" << std::endl;
        return 1;
    }

    // Show zoom movement (changing position).
    for (int i = 0; i < PRINT_COUNT; ++i)
    {
        std::cout << "Zoom pos: " <<
                     lens->getParam(rapidpixel::LensParam::ZOOM_POS) <<
                     std::endl;
        std::this_thread::sleep_for(
                    std::chrono::milliseconds(PRINT_PERIOD_MSEC));
    }

    return 0;
}

Test application

Rpl/test folder contains a test application which allows to control the lens of the Rpl library from the terminal. The application doesn’t show video and doesn’t have a graphical user interface: the lens is controlled by commands typed in the terminal. The source code is in the file test/main.cpp. The serial port name, the baud rate and the timeout are given as arguments (RplTest <port> [baud [timeout]]) or entered in the dialog at the start of the application. The application opens the lens and prints the messages of the library to the terminal (LOG_MODE is set to 1). The lens controller detects the hardware limits of zoom and focus after the start (a few seconds): commands wait for it. Commands of the application (names of the params and commands are not case sensitive, a param or a command can be given by the number):

Command Description
help Show the commands, the params and the lens commands.
params Show the values of all params which can be read.
get Show the value of a param, for example get ZOOM_POS.
set Set the value of a param, for example set ZOOM_SPEED 20. The value must be a finite number.
cmd [argument] Execute a lens command, for example cmd ZOOM_TO_POS 65535 or cmd FOCUS_STOP.
status Show the open and connection status.
watch [seconds] Show the zoom, focus and iris positions every 0.5 sec (10 sec by default, 600 sec maximum).
open [port [baud [timeout]]] Open the lens (after close).
close Close the lens.
quit Exit (the end of the input also exits).

The autofocus needs video frames which the application doesn’t provide: the autofocus commands and params are accepted but the autofocus doesn’t run. The application returns 0 if it exits normally and 1 if the arguments are not valid or the lens can’t be opened.


Table of contents