
SunnyLens C++ library
v1.2.0
Table of contents
- Overview
- Versions
- Library files
- SunnyLens class description
- SunnyLens class declaration
- getVersion method
- openLens method
- initLens method
- closeLens method
- isLensOpen method
- isLensConnected method
- setParam method
- getParam method
- getParams method
- executeCommand method
- addVideoFrame method
- decodeAndExecuteCommand method
- encodeSetParamCommand method of Lens class
- encodeCommand method of Lens class
- decodeCommand method of Lens class
- Data structures
- LensParams class description
- Build and connect to your project
- Portability
- Simple example
- Test application
Overview
SunnyLens C++ library is a software controller for Sunny continuous zoom lenses. The SunnyLens library inherits Lens interfaces. It depends on libraries: Lens (provides interface and data structures to control lenses), Logger (provides function to print logs), SerialPort (provides functions to work with serial ports), SunnyLensParser (provides functions to encode control commands and decode responses from Sunny continuous zoom lenses; it is a part of the SunnyLens 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 doesn’t contain the source code of the other dependencies: they are added to the build as described in the section Build and connect to your project. The SunnyLens library provides a simple interface to be integrated into any C++ project. The library doesn’t have third-party dependencies to be specially installed in OS. It is developed with the C++17 standard and is compatible with Linux and Windows.
SunnyLens 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 | 15.07.2024 | First version. |
| 1.0.1 | 25.07.2024 | - Add auto focus. |
| 1.0.2 | 29.07.2024 | - Submodules updated. - CMake changed. |
| 1.0.3 | 18.09.2024 | - AFEngine submodule update. |
| 1.0.4 | 05.12.2024 | - Linkage option add. |
| 1.0.5 | 10.12.2024 | - Update Linkage behavior. |
| 1.0.6 | 17.02.2025 | - Lens type detection added. |
| 1.0.7 | 13.03.2025 | - AFEngine noise reduction switched on by default. |
| 1.0.8 | 03.04.2025 | - Logger submodule update. |
| 1.0.9 | 30.04.2025 | - Add zoom inverted flag as IRIS_MODE parameter. |
| 1.0.10 | 13.05.2025 | - Add filter mode as Noise reduction for AF procedure. |
| 1.0.11 | 26.10.2025 | - SerialPort submodule updated. - SunnyLensParser submodule updated. - Fix code mistakes. |
| 1.0.12 | 28.03.2026 | - AFEngine submodule updated. |
| 1.0.13 | 29.05.2026 | - Fix ROI handling: AF ROI driven by CUSTOM_1 is recomputed per frame, explicit AF_ROI_X0/Y0/X1/Y1 disables auto-recompute. - Allow to set 0 for CUSTOM_1 for enabling auto ROI. - Add divide-by-zero guards in speed / position scaling formulas. - Make setParam(ZOOM_POS/HW_POS/FOCUS_POS/HW_POS) symmetric to executeCommand(ZOOM_TO_POS/FOCUS_TO_POS) regarding IRIS_MODE inversion and CUSTOM_3 linkage state transitions. - Fix getParam(AF_ROI_X1) auto-mode formula. - Fix CUSTOM_3 setParam: do not push uninitialised data when value == 1, do not unconditionally re-enable linkage on reconnect. - Fix robust comparison of CUSTOM_3 against LinkageStatus enum. - Pass explicit afRoiX0/Y0/X1/Y1 from initLens to the controller. - Refactor: extract recomputeUserZoomPos/recomputeUserFocusPos helpers. |
| 1.1.0 | 01.07.2026 | - AFEngine submodule updated. - Critical bugs fixed. |
| 1.1.1 | 13.07.2026 | - AFEngine submodule updated. - Fixed auto focus accuracy on low contrast objects. |
| 1.1.2 | 17.10.2026 | - Git submodules removed: the dependencies are expected next to the repository. - Unused CMake option SUNNY_LENS_DEMO_MODE removed. - Fixed integer overflow in conversion of zoom / focus hardware positions and speeds from the lens to user values. - NaN and values outside of the range are rejected by setParam(…) and executeCommand(…) (the conversion of such values to int was undefined). - decodeAndExecuteCommand(…) returns FALSE if the pointer to data is nullptr. - The buffer of commands for the lens is limited to 1024 commands. - getParam(LOG_MODE) returns the current logging mode. - openLens(…) checks the baudrate (> 0) and the timeout (>= 0), start of the communication thread is protected against failures, openLens(…) and closeLens(…) are serialized. - Communication thread: monotonic clock for the request period, bounded reading of the serial port buffer at start (closeLens(…) and the destructor waited forever if the lens sent data without a pause), the counter of missing responses is saturated, an exception can’t leave the thread. - Call of setParam(FILTER_MODE) removed from initLens(…) (the parameter is not supported). - Compiler and linker hardening options, strict warnings, standard C++ only. - Example and test application reworked. The test application doesn’t enable log file by default. |
| 1.2.0 | 29.10.2026 | - The SunnyLensParser library is a part of the repository (folder src/parser) and is not a separate dependency any more. |
Library files
The library supplied by source code only. The user would be given a set of files in the form of a CMake project (repository). 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.
SunnyLens.h ----------------------------- Main library header file.
SunnyLens.cpp --------------------------- C++ implementation file.
SunnyLensVersion.h ---------------------- Header file with library version.
SunnyLensVersion.h.in ------------------- CMake service file to generate version header.
parser ---------------------------------- Protocol parser library (former SunnyLensParser 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 SunnyLensParser).
SunnyLensParser.cpp ------------- C++ implementation file of the parser library.
SunnyLensParser.h --------------- Main header file of the parser library (SunnyLensParser class declaration).
SunnyLensParserVersion.h -------- Header file with version of the parser library.
SunnyLensParserVersion.h.in ----- CMake service file to generate version header of the parser library.
static ------------------------------ Folder with images of the parser documentation.
sunny_lens_parser_web_logo.png -- Logo of the parser library.
test -------------------------------- Folder with test application of the parser (not built by SunnyLens).
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 images used in this document.
SunnyLens class description
SunnyLens class declaration
SunnyLens.h file contains SunnyLens class declaration:
namespace rapidpixel
{
/// Sunny lens controller class.
class SunnyLens : public Lens
{
public:
/// Class constructor.
SunnyLens();
/// Class destructor.
~SunnyLens() override;
/// Copy constructor is deleted.
SunnyLens(const SunnyLens&) = delete;
/// Move constructor is deleted.
SunnyLens(SunnyLens&&) = delete;
/// Copy assignment operator is deleted.
SunnyLens& operator= (const SunnyLens&) = delete;
/// Move assignment operator is deleted.
SunnyLens& operator= (SunnyLens&&) = delete;
/// Get class version.
static std::string getVersion();
/// Open serial 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;
};
}
getVersion method
The getVersion() method returns string of current version of SunnyLens class. Method declaration:
static std::string getVersion();
Method can be used without SunnyLens class instance. Example:
std::cout << "SunnyLens version: " << rapidpixel::SunnyLens::getVersion() << std::endl;
Console output:
SunnyLens version: 1.2.0
openLens method
The openLens(…) method opens the serial port to communicate with Sunny lenses. If the serial port is already open, the method will return TRUE. Lens parameters will be initialized by default. To initialize lens controller by set of parameters the initLens(…) method can be used. After successful initialization the library will run communication thread (thread to communicate with lens equipment via serial port). The methods openLens(…), initLens(…) and closeLens() can be called from any thread, opening and closing of the lens are serialized. Method declaration:
bool openLens(std::string initString) override;
| Parameter | Value |
|---|---|
| initString | Initialization string contains full serial port name, baudrate, timeout (milliseconds to wait for lens data) separated by “;”. Example: “/dev/ttyUSB0;115200;50”. Empty elements are skipped. Baudrate and timeout optional params and will be set by default by the library if not provided (115200 and 50). The baudrate must be a number greater than 0, the timeout must be a number not less than 0. |
Returns: TRUE if the lens controller is initialized (also if it was initialized before) or FALSE if not. FALSE is returned if the initialization string is not valid or the serial port can’t be opened.
initLens method
The initLens(…) initializes lens controller and sets lens params (Lens interface). The method will set given lens params and after will call openLens(…) method. A param with a value that is not valid (see Table 3) is skipped and keeps its current value. After successful initialization the library will run communication thread (thread to communicate with equipment via serial port). Method declaration:
bool initLens(LensParams& params) override;
| Parameter | Value |
|---|---|
| params | LensParams class object which includes all lens parameters. LensParams class includes initString which 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 serial port and stops all communication threads. Method declaration:
void closeLens() override;
isLensOpen method
The isLensOpen() method returns the lens controller initialization status. Open status shows whether the controller is initialized (serial port open) but doesn’t show whether the controller has communication with lens equipment. For example, the serial port may be open (the serial port file in OS is open) but the equipment may be inactive (no power). In this case 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 whether the lens controller receives responses from the equipment. For example, the serial port may be open but the equipment inactive (no power). In this case the isLensOpen(…) method will return TRUE but the isLensConnected() method will return FALSE. 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 new lens parameters value. SunnyLens provides thread-safe setParam(…) method call. This means that the setParam(…) method can be safely called from any thread. The lens controller checks if parameters ID and parameter value are valid and adds them to internal buffer. A value that is NaN or is outside of the range of the parameter (see Table 3) is rejected: the method returns FALSE and the lens controller is not changed. If parameter ID and parameter argument are valid the method will return TRUE but parameters may not be set (some params related only to lens controller but not lens hardware). Internal communication thread takes parameters (if parameters related to lens hardware) from internal buffer and send it to lens. The internal buffer holds up to 1024 commands: if the lens doesn’t receive commands (the serial port is not open or the lens doesn’t answer) and the buffer is full, the oldest command is dropped. 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 (accepted by lens controller) or FALSE if not.
getParam method
The getParam(…) method returns lens parameter value. SunnyLens provides thread-safe getParam(…) method call. This means that the getParam(…) method can be safely called from any thread. 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).
getParams method
The getParams(…) method returns all lens parameters. SunnyLens provides thread-safe getParams(…) method call. This means that the getParams(…) method can be safely called from any thread. Method declaration:
void getParams(LensParams& params) override;
| Parameter | Description |
|---|---|
| params | Reference to LensParams class object which includes all lens parameters. |
executeCommand method
The executeCommand(…) method to execute lens action command. SunnyLens provides thread-safe executeCommand(…) method call. This means that the executeCommand(…) method can be safely called from any thread. The lens controller checks if command ID and command argument are valid and adds them to internal buffer. A command argument that is NaN or is outside of the range of the command (see Table 2) is rejected: the method returns FALSE. If command ID and command argument are valid the method will return TRUE but command may not be executed. Internal communication thread takes commands from internal buffer and send commands to lens. The internal buffer is shared with setParam(…): it holds up to 1024 commands and the oldest command is dropped if the buffer is full. 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 accepted by lens controller or FALSE if not.
addVideoFrame method
The addVideoFrame(…) method copies video frame data to lens controller to perform autofocus algorithm. To perform auto focus lens the controller calculates focus factor in auto focus ROI (focus factor can be obtained with getParam(…) method and parameters FOCUS_FACTOR, or with getParams(…) method). To calculate focus factor SunnyLens needs video frame, so to use auto focus functions the method addVideoFrame(…) must be called for each captured video frame. Method declaration:
void addVideoFrame(rapidpixel::Frame& frame) override;
| Parameter | Description |
|---|---|
| frame | Video Frame object. The library supports RAW pixel formats: BGR24, RGB24, GRAY, NV12, NV21, YU12, YV12, UYVY, YUYV and YUV24. Minimum width / height of video frame is 32. Maximum width / height of video frame is 8192. |
decodeAndExecuteCommand method
The decodeAndExecuteCommand(…) method decodes and executes command on lens controller side. Method will decode commands which encoded by encodeCommand(…) or encodeSetParamCommand(…) methods of Lens interface class. If command decoded the method will call setParam(…) or executeCommand(…) methods. This method is thread-safe, so the method can be safely called from any thread. The method returns FALSE if the pointer to the data is nullptr, the size is not valid or the command is not valid. Method declaration:
bool decodeAndExecuteCommand(uint8_t* data, int size) override;
| Parameter | Description |
|---|---|
| data | Pointer to input command. Must not be nullptr and must be valid for size bytes. To generate input command you may use encodeCommand(…) and encodeSetParamCommand(…) static methods. |
| size | Size of command. Must be 11 bytes for SET_PARAM and COMMAND. |
Returns: TRUE if command decoded (change parameter command or action command) and executed (action command or set param command).
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. |
| size | Size of encoded data. Will be 11 bytes. |
| 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;
// Random parameter value.
float outValue = static_cast<float>(std::rand() % 20);
// Encode command.
rapidpixel::Lens::encodeSetParamCommand(data, size, rapidpixel::LensParam::AF_ROI_X0, outValue);
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. |
| size | Size of encoded data. Will be 11 bytes. |
| 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;
// Random command argument value.
float outValue = static_cast<float>(std::rand() % 20);
// Encode command.
rapidpixel::Lens::encodeCommand(data, size, rapidpixel::LensCommand::ZOOM_TO_POS, outValue);
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. |
| size | Size of command. Should be 11 bytes. |
| paramId | Lens parameter ID according to LensParam enum. After decoding SET_PARAM command the method will return parameter ID. |
| commandId | Lens command ID according to LensCommand enum. After decoding COMMAND the method will return command ID. |
| value | Lens parameter value (after decoding SET_PARAM command) or lens command argument (after decoding COMMAND). |
Returns: 0 - in case decoding COMMAND, 1 - in case decoding SET_PARAM command or -1 in case errors.
Data structures
LensCommand enum
LensCommand enum declared in Lens.h file. Enum declaration:
namespace rapidpixel
{
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 | Not supported by SunnyLens class. |
| IRIS_CLOSE | Not supported by SunnyLens class. |
| IRIS_TO_POS | Not supported by SunnyLens class. |
| IRIS_STOP | Not supported by SunnyLens class. |
| AF_START | Start autofocus. Command doesn’t have arguments. |
| AF_STOP | Stop autofocus. Command doesn’t have arguments. |
| RESTART | Not supported by SunnyLens class. |
| DETECT_HW_RANGES | Calibrate auto focus engine. Command doesn’t have arguments. |
LensParam enum
Enum declaration:
namespace rapidpixel
{
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 terminal, 2 - Only file,
/// 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 parameters description. Some parameters 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 hardware position (encoder position). Param argument: zoom position ZOOM_HW_WIDE_LIMIT - ZOOM_HW_TELE_LIMIT. 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 hardware position. Setting a parameter move focus to hardware position (encoder position). Parameter value: focus position FOCUS_HW_NEAR_LIMIT - FOCUS_HW_FAR_LIMIT. 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 | Not supported by SunnyLens class. |
| IRIS_HW_POS | read / write | Not supported by SunnyLens class. |
| FOCUS_MODE | read / write | Focus mode: 0 - Manual focus control (user can adjust focus position only manually). 1 - Push auto focus mode (manual focus position control and auto focus by command only). 2 - Continuous auto focus mode (auto start auto focus algorithm after zoom position changes). |
| FILTER_MODE | read / write | Not supported by SunnyLens class. |
| AF_ROI_X0 | read / write | Autofocus ROI top-left corner horizontal position, pixels. Valid values of AF_ROI_X0/Y0/X1/Y1 for setParam(…): 0 - 65535. By default the ROI is centered and sized as CUSTOM_1 percent of frame width / height - it is recomputed on every video frame in addVideoFrame(). Writing AF_ROI_X0/Y0/X1/Y1 explicitly pins the ROI to user-supplied coordinates and disables this auto-recompute. Writing CUSTOM_1 again returns the controller to the centered auto-recompute mode. |
| AF_ROI_Y0 | read / write | Autofocus ROI top-left corner vertical position, pixels. See AF_ROI_X0 for behavior. |
| AF_ROI_X1 | read / write | Autofocus ROI bottom-right corner horizontal position, pixels. See AF_ROI_X0 for behavior. |
| AF_ROI_Y1 | read / write | Autofocus ROI bottom-right corner vertical position, pixels. See AF_ROI_X0 for behavior. |
| 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 (100 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. Valid values: from 0 to 100 (default 100). 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 50 to FOCUS_HW_MAX_SPEED (100 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. Valid values: from 50 to 100 (default 100). 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 SunnyLens class. |
| IRIS_HW_SPEED | read / write | Not supported by SunnyLens class. |
| IRIS_HW_MAX_SPEED | read / write | Not supported by SunnyLens class. |
| ZOOM_HW_TELE_LIMIT | read / write | Zoom hardware tele limit. Default value 15000. The library requests this value from lens hardware periodically (about every 400 ms) and each answer of the lens replaces the value (a value set by the user is kept until the next answer). Valid values for setParam(…): from the zoom hardware wide limit to 64000. |
| ZOOM_HW_WIDE_LIMIT | read / write | Zoom hardware wide limit. Default value 0. The value is not requested from lens hardware. Valid values for setParam(…): from 0 to the zoom hardware tele limit. |
| FOCUS_HW_FAR_LIMIT | read / write | Focus hardware far limit. Default value 6500. The library requests this value from lens hardware periodically (about every 400 ms) and each answer of the lens replaces the value (a value set by the user is kept until the next answer). Valid values for setParam(…): from the focus hardware near limit to 64000. |
| FOCUS_HW_NEAR_LIMIT | read / write | Focus hardware near limit. Default value 0. The value is not requested from lens hardware. Valid values for setParam(…): from 0 to the focus hardware far limit. |
| IRIS_HW_OPEN_LIMIT | read / write | Not supported by SunnyLens class. |
| IRIS_HW_CLOSE_LIMIT | read / write | Not supported by SunnyLens class. |
| 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 / write | Focus hardware speed in autofocus mode range from 0 to 100. Default value 20. |
| 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 | Zoom inverted flag. Value: 0 - zoom not inverted, 1 - zoom inverted. |
| 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 SunnyLens class. |
| STABILIZER_MODE | read / write | Not supported by SunnyLens class. |
| AF_RANGE | read only | Focal length in millimetres. |
| X_FOV_DEG | read / write | Not supported by SunnyLens class. |
| Y_FOV_DEG | read / write | Not supported by SunnyLens class. |
| LOG_MODE | read / write | Logging mode. Values: 0 - Disable. 1 - Only terminal. 2 - Only file. 3 - File and terminal. |
| 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 | Lens type. Model number. The value is only stored by the lens controller (integer values). |
| CUSTOM_1 | read / write | Percent of central ROI for AF Engine. Value: 0-100. Writing this parameter switches the autofocus ROI to the centered “from CUSTOM_1” mode - the ROI rectangle (CUSTOM_1% of frame width and height, centered) is recomputed on every video frame. If value is 0, it enables auto ROI. To pin a custom ROI, write AF_ROI_X0/Y0/X1/Y1 explicitly. |
| CUSTOM_2 | read / write | Time adjustment for AF Engine, ms. Valid values: from -500 to 500. |
| CUSTOM_3 | read / write | Zoom\Focus linkage status. Values: 0 - Unlinked. 1 - Temporary unlinked. 2 - Linked. |
LensParams class description
LensParams class used for lens controller initialization (initLens(…) method) or to get all actual params (getParams() method). Also LensParams provides methods 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
{
/// Field of view point class.
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)
/// Special member functions.
FovPoint() = default;
FovPoint(const FovPoint& src) = default;
FovPoint(FovPoint&& src) = default;
FovPoint& operator= (const FovPoint& src) = default;
FovPoint& operator= (FovPoint&& src) = default;
};
/// Lens params class.
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 terminal, 2 - Only file,
/// 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)
/// Default constructor.
LensParams() = default;
/// Copy constructor.
LensParams(const LensParams& src) = default;
/// Move constructor.
LensParams(LensParams&& src) = default;
/// Copy assignment operator.
LensParams& operator= (const LensParams& src) = default;
/// Move assignment operator.
LensParams& operator= (LensParams&& src) = default;
/// Encode (serialize) params.
bool encode(uint8_t* data, int bufferSize, int& size,
LensParamsMask* mask = nullptr);
/// Decode (deserialize) params.
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;115200;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). Zoom speed can be set by setParam(…) method. The zoom position changes only when the lens moves. |
| zoomHwPos | int | Hardware zoom position. The zoom position changes only when the lens moves. |
| focusPos | int | Focus position: 0 (full near) - 65535 (full far). Focus speed can be set by setParam(…) method. The focus position changes only when the lens moves. |
| focusHwPos | int | Focus hardware position. The focus position changes only when the lens moves. |
| irisPos | int | Not supported by SunnyLens class. |
| irisHwPos | int | Not supported by SunnyLens class. |
| focusMode | int | Focus mode: 0 - Manual focus control (user can adjust focus position only manually). 1 - Push auto focus mode (manual focus position control and auto focus by command only). 2 - Continuous auto focus mode (auto start auto focus algorithm after zoom position changes). |
| filterMode | int | Not supported by SunnyLens class (getParams(…) returns 100). |
| afRoiX0 | int | Autofocus ROI top-left corner horizontal position, pixels. By default the ROI is centered and sized as custom1 percent of frame width / height - recomputed on every video frame in addVideoFrame(). Writing afRoiX0/Y0/X1/Y1 explicitly pins the ROI to user-supplied coordinates and disables auto-recompute. Writing custom1 returns the controller to the centered auto-recompute mode. |
| afRoiY0 | int | Autofocus ROI top-left corner vertical position, pixels. See afRoiX0 for behavior. |
| afRoiX1 | int | Autofocus ROI bottom-right corner horizontal position, pixels. See afRoiX0 for behavior. |
| afRoiY1 | int | Autofocus ROI bottom-right corner vertical position, pixels. See afRoiX0 for behavior. |
| 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 zoomHwMaxSpeed (100 by default). |
| zoomHwMaxSpeed | int | Maximum zoom hardware speed. Default value 100. |
| 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 50 to focusHwMaxSpeed (100 by default). |
| focusHwMaxSpeed | int | Maximum focus hardware speed. Default value 100. |
| irisSpeed | int | Not supported by SunnyLens class. |
| irisHwSpeed | int | Not supported by SunnyLens class. |
| irisHwMaxSpeed | int | Not supported by SunnyLens class. |
| zoomHwTeleLimit | int | Zoom hardware tele limit. Default value 15000. The library requests this value from lens hardware periodically (about every 400 ms) and each answer of the lens replaces the value (a value set by the user is kept until the next answer). Valid values for setParam(…): from the zoom hardware wide limit to 64000. |
| zoomHwWideLimit | int | Zoom hardware wide limit. Default value 0. The value is not requested from lens hardware. Valid values for setParam(…): from 0 to the zoom hardware tele limit. |
| focusHwFarLimit | int | Focus hardware far limit. Default value 6500. The library requests this value from lens hardware periodically (about every 400 ms) and each answer of the lens replaces the value (a value set by the user is kept until the next answer). Valid values for setParam(…): from the focus hardware near limit to 64000. |
| focusHwNearLimit | int | Focus hardware near limit. Default value 0. The value is not requested from lens hardware. Valid values for setParam(…): from 0 to the focus hardware far limit. |
| irisHwOpenLimit | int | Not supported by SunnyLens class. |
| irisHwCloseLimit | int | Not supported by SunnyLens class. |
| focusFactor | float | Focus factor if it was calculated, otherwise -1. |
| isConnected | bool | Lens connection status. Connection status shows if the lens controller has data exchange with lens equipment. |
| afHwSpeed | int | Focus hardware speed in autofocus mode range from 0 to 100. Default value 20. |
| 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 | Zoom inverted flag. Value: 0 - zoom not inverted, 1 - zoom inverted. |
| autoAfRoiWidth | int | ROI width (pixels) for autofocus algorithm when lens controller detects ROI position automatically. Value: from 8 to (video frame width - autoAfRoiBorder * 2). |
| autoAfRoiHeight | int | ROI height (pixels) for autofocus algorithm when lens controller detects ROI position automatically. Value: from 8 to (video frame height - autoAfRoiBorder * 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 SunnyLens class. |
| stabiliserMode | int | Not supported by SunnyLens class. |
| afRange | int | Focal length in millimetres. (read only) |
| xFovDeg | float | Not supported by SunnyLens class. |
| yFovDeg | float | Not supported by SunnyLens 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. |
| type | int | Lens type. Model number. |
| custom1 | float | Percent of central ROI for AF Engine. Value: 1-100. Writing this parameter switches the autofocus ROI to the centered “from custom1” mode - the ROI rectangle (custom1% of frame width and height, centered) is recomputed on every video frame in addVideoFrame(). To pin a custom ROI, write afRoiX0/Y0/X1/Y1 explicitly. |
| custom2 | float | Time adjustment for AF Engine, ms. Valid values: from -500 to 500. |
| custom3 | float | Zoom\Focus linkage status. Values: 0 - Unlinked. 1 - Temporary unlinked. 2 - Linked. |
| fovPoints | FovPoint | Not supported by SunnyLens class. |
Note: LensParams class fields listed 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. |
| size | Size of encoded data. |
| bufferSize | Data buffer size. Buffer size must be >= 201 bytes. |
| 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 in the LensParamsMask structure. |
LensParamsMask structure declaration:
typedef struct LensParamsMask
{
bool zoomPos{true};
bool zoomHwPos{true};
bool focusPos{true};
bool focusHwPos{true};
bool irisPos{true};
bool irisHwPos{true};
bool focusMode{true};
bool filterMode{true};
bool afRoiX0{true};
bool afRoiY0{true};
bool afRoiX1{true};
bool afRoiY1{true};
bool zoomSpeed{true};
bool zoomHwSpeed{true};
bool zoomHwMaxSpeed{true};
bool focusSpeed{true};
bool focusHwSpeed{true};
bool focusHwMaxSpeed{true};
bool irisSpeed{true};
bool irisHwSpeed{true};
bool irisHwMaxSpeed{true};
bool zoomHwTeleLimit{true};
bool zoomHwWideLimit{true};
bool focusHwFarLimit{true};
bool focusHwNearLimit{true};
bool irisHwOpenLimit{true};
bool irisHwCloseLimit{true};
bool focusFactor{true};
bool isConnected{true};
bool afHwSpeed{true};
bool focusFactorThreshold{true};
bool refocusTimeoutSec{true};
bool afIsActive{true};
bool irisMode{true};
bool autoAfRoiWidth{true};
bool autoAfRoiHeight{true};
bool autoAfRoiBorder{true};
bool afRoiMode{true};
bool extenderMode{true};
bool stabiliserMode{true};
bool afRange{true};
bool xFovDeg{true};
bool yFovDeg{true};
bool logMode{true};
bool temperature{true};
bool isOpen{true};
bool type{true};
bool custom1{true};
bool custom2{true};
bool custom3{true};
} 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 params" << std::endl;
}
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 params" << std::endl;
}
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. Method declaration:
bool decode(uint8_t* data, int dataSize);
| Parameter | Value |
|---|---|
| data | Pointer to data buffer. |
| dataSize | Size of data. |
Returns: TRUE if data decoded (deserialized) or FALSE if not.
Example:
// Encode data.
rapidpixel::LensParams in;
uint8_t data[1024];
int size = 0;
if (!in.encode(data, 1024, size))
{
std::cout << "Can't encode params" << std::endl;
}
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;
}
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 random params.
rapidpixel::LensParams in;
for (int i = 0; i < 5; ++i)
{
rapidpixel::FovPoint pt;
pt.hwZoomPos = std::rand() % 255;
pt.xFovDeg = static_cast<float>(std::rand() % 255);
pt.yFovDeg = static_cast<float>(std::rand() % 255);
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 config 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": 163,
"xFovDeg": 151.0,
"yFovDeg": 162.0
},
{
"hwZoomPos": 85,
"xFovDeg": 83.0,
"yFovDeg": 190.0
},
{
"hwZoomPos": 241,
"xFovDeg": 252.0,
"yFovDeg": 249.0
},
{
"hwZoomPos": 121,
"xFovDeg": 107.0,
"yFovDeg": 82.0
},
{
"hwZoomPos": 20,
"xFovDeg": 19.0,
"yFovDeg": 233.0
}
]
}
}
Build and connect to your project
Build stand alone
The repository does not contain sub-repositories. The libraries SunnyLens depends on (Frame, ConfigReader, AFEngine, SerialPort, Lens and Logger) must be cloned into the same folder as SunnyLens. The folder structure must be:
<work folder>
SunnyLens
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 <SunnyLens 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 SunnyLens
mkdir build
cd build
cmake ..
make
On Windows use cmake --build . --config Release instead of make. If SunnyLens 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 does not exist CMake stops with an error.
The SunnyLensParser 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 SunnyLens adds the folder src/parser before the library in every build (stand alone and when SunnyLens 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 SunnyLens is the top-level project).
| Option | Default | Description |
|---|---|---|
| ${PARENT}_SUNNY_LENS | ON | Build the library. |
| ${PARENT}_SUNNY_LENS_TEST | ON (stand alone), OFF (included in other project) | Build the test application. |
| ${PARENT}_SUNNY_LENS_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 SunnyLens as a sub-repository. |
| CMAKE_BUILD_TYPE | Release (if not specified) | Build type. |
Connect to your project
If you want to connect SunnyLens library to your CMake project as source code, you can do the following. For example, if your repository has structure:
CMakeLists.txt
src
CMakeList.txt
yourLib.h
yourLib.cpp
Create folder 3rdparty and copy folders of SunnyLens repository and of the repositories it depends on there (Frame, ConfigReader, AFEngine, SerialPort, Lens and Logger). New structure of your repository:
CMakeLists.txt
src
CMakeList.txt
yourLib.h
yourLib.cpp
3rdparty
SunnyLens
Frame
ConfigReader
AFEngine
SerialPort
Lens
Logger
Create CMakeLists.txt file in 3rdparty folder. CMakeLists.txt should be containing:
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_EXAMPLES OFF CACHE BOOL "" FORCE)
SET(${PARENT}_CONFIG_READER_TESTS 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_SUNNY_LENS ON CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_SUNNY_LENS)
SET(${PARENT}_SUNNY_LENS ON CACHE BOOL "" FORCE)
SET(${PARENT}_SUNNY_LENS_TEST OFF CACHE BOOL "" FORCE)
SET(${PARENT}_SUNNY_LENS_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_SUNNY_LENS)
add_subdirectory(SunnyLens)
endif()
File 3rdparty/CMakeLists.txt adds the folders of the dependencies and the folder SunnyLens to your project (in this order: the dependencies first) and excludes test applications and examples from compiling (by default test application and example excluded from compiling if SunnyLens included as sub-repository). SunnyLens doesn’t add the other libraries it depends on when it is included in another project: they must be added by your project as shown above. If the dependencies are not added, the build stops with an error that a header file of a dependency can’t be found (for example “AFEngine.h: No such file or directory”). The new structure of your repository will be:
CMakeLists.txt
src
CMakeList.txt
yourLib.h
yourLib.cpp
3rdparty
CMakeLists.txt
SunnyLens
Frame
ConfigReader
AFEngine
SerialPort
Lens
Logger
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 SunnyLens library in your src/CMakeLists.txt file:
target_link_libraries(${PROJECT_NAME} SunnyLens)
Done!
Portability
The library was built and tested on little endian hosts: Linux x86-64 (GCC 12, GCC 13, Clang 15, Clang 18), Linux AArch64 (GCC 13 cross build, tests run with QEMU) and Windows x86-64 (MSVC 2022). The commands for the lens are encoded and the answers of the lens are decoded by the SunnyLensParser library byte by byte in the byte order of the lens protocol, so the data exchange with the lens does not depend on the byte order of the host. The commands of decodeAndExecuteCommand(…) (encoded by the Lens class) store int and float values in the byte order of the host. The library has no SIMD code and no CPU specific compiler options.
Simple example
A simple application shows how to use the SunnyLens library. The serial port initialization string (port name, baudrate and timeout separated by “;”) can be given as the first command line argument, the default value is “/dev/ttyUSB0;115200;50”.
#include <chrono>
#include <iostream>
#include <string>
#include <thread>
#include "Lens.h"
#include "SunnyLens.h"
namespace
{
/// Serial port init string: port name, baudrate and timeout (ms) separated by
/// ";". The port name can be replaced by the first command line argument.
const char* const DEFAULT_INIT_STRING{"/dev/ttyUSB0;115200;50"};
/// Maximum time to wait for the first answer of the lens, ms.
constexpr int CONNECT_TIMEOUT_MS{5000};
/// Time to wait for the answers of the lens with the zoom limits, ms (the
/// requests are sent every 400 ms).
constexpr int LIMITS_WAIT_MS{1000};
/// Zoom speed, percent (0 - 100).
constexpr float ZOOM_SPEED{10.0f};
/// Zoom position that corresponds to the full tele (0 - 65535).
constexpr float ZOOM_FULL_TELE{65535.0f};
/// The zoom is considered to be moved to the position if the difference is
/// not larger than this value.
constexpr float ZOOM_TOLERANCE{100.0f};
/// Maximum time of the zoom movement, ms.
constexpr int ZOOM_TIMEOUT_MS{60000};
/// Period of printing the zoom position, ms.
constexpr int PRINT_PERIOD_MS{100};
}
int main(int argc, char** argv)
{
std::string initString{DEFAULT_INIT_STRING};
if (argc > 1)
{
initString = argv[1];
}
// Init lens controller.
rapidpixel::SunnyLens lens;
if (!lens.openLens(initString))
{
std::cout << "ERROR: Can't open lens " << initString << std::endl;
return -1;
}
// Wait for the answer of the lens.
for (int waitedMs = 0;
waitedMs < CONNECT_TIMEOUT_MS && !lens.isLensConnected();
waitedMs += PRINT_PERIOD_MS)
{
std::this_thread::sleep_for(std::chrono::milliseconds(PRINT_PERIOD_MS));
}
if (!lens.isLensConnected())
{
std::cout << "ERROR: No answer from the lens" << std::endl;
lens.closeLens();
return -1;
}
// The library requests the zoom limits from the lens periodically. The
// position command uses the limits, so wait for the first answers.
std::this_thread::sleep_for(std::chrono::milliseconds(LIMITS_WAIT_MS));
// 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;
lens.closeLens();
return -1;
}
// Go to zoom position 65535 (Full tele).
if (!lens.executeCommand(rapidpixel::LensCommand::ZOOM_TO_POS,
ZOOM_FULL_TELE))
{
std::cout << "ERROR: Can't move zoom" << std::endl;
lens.closeLens();
return -1;
}
// Show zoom movement (changing position) until the position is reached.
bool reached = false;
for (int movedMs = 0; movedMs < ZOOM_TIMEOUT_MS && !reached; movedMs += PRINT_PERIOD_MS)
{
const float zoomPos = lens.getParam(rapidpixel::LensParam::ZOOM_POS);
std::cout << "Zoom pos: " << zoomPos << std::endl;
reached = ZOOM_FULL_TELE - zoomPos <= ZOOM_TOLERANCE;
std::this_thread::sleep_for(std::chrono::milliseconds(PRINT_PERIOD_MS));
}
lens.closeLens();
if (!reached)
{
std::cout << "ERROR: Zoom position is not reached" << std::endl;
return -1;
}
return 0;
}
Test application
SunnyLens/test folder contains a test application which allows to control the lens from the terminal. The application doesn’t use a graphical interface and doesn’t show video. The serial port name and the baudrate are given as the first and the second command line arguments or are entered after the start (the default values are shown in square brackets). The test application opens the lens, waits up to 5 seconds for the first answer of the lens and shows the main menu:
1 - Set lens param
2 - Get lens param
3 - Execute lens command
4 - Print all lens params
-1 - Exit
Menu items 1 and 2 show the list of the lens parameters supported by SunnyLens (ID and name), the user enters the ID of the parameter and (to set the parameter) the value. The menu item 3 shows the list of the lens commands and the user enters the ID of the command and (for the commands with an argument) the argument:
Zoom tele - move zoom tele.
Zoom wide - move zoom wide.
Zoom to position - move zoom to the position (0 - 65535).
Zoom stop - stop zoom moving.
Focus far - move focus far.
Focus near - move focus near.
Focus to position - move focus to the position (0 - 65535).
Focus stop - stop focus moving.
Start autofocus - start autofocus.
Stop autofocus - stop autofocus.
Detect hardware ranges - calibrate the auto focus engine.
The menu item 4 prints all the parameters of the LensParams class that SunnyLens supports. The test application doesn’t write files unless the logging to file is switched on by the parameter LOG_MODE (the logging is switched off by default). The application exits when -1 is entered in the main menu or the standard input is closed. The exit code is 0 after a normal exit and 1 if the lens can’t be opened.