lrf_web_logo

Lrf interface C++ library

v1.0.2

Table of contents

Overview

Lrf C++ library provides standard interface as well defines data structures and rules for different laser range finder (LRF) software controllers. Lrf interface class does nothing, just provides interface and provides methods to encode / decode commands and encode / decode params. Different LRF controllers inherit interface from Lrf C++ class. Lrf.h file contains list of data structures (LrfCommand enum, LrfParam enum and LrfParams class) and Lrf class declaration. LrfCommand enum contains IDs of action commands supported by Lrf class. LrfParam enum contains IDs of parameters supported by Lrf class. LrfParams class contains fields for LRF parameters values and provides methods to encode/decode and read/write LRF parameters from JSON file. All LRF controllers should include params and commands listed in Lrf.h file. Lrf interface class depends only on ConfigReader library (provides methods to read / write JSON config files). The ConfigReader library must be cloned next to the Lrf repository (see Build and connect to your project section). It uses C++17 standard.

Lrf 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.

Versions

Table 1 - Library versions.

Version Release date What’s new
1.0.0 20.06.2024 First version
1.0.1 30.07.2024 - CMake updated.
1.0.2 19.10.2026 - Git submodules removed: the ConfigReader library must be cloned next to the Lrf repository.
- LrfParams::encode(…): the buffer size is checked against the maximum size of the encoded data (72 bytes). The check used 69 bytes, so up to 3 bytes were written outside of a buffer of 69 - 71 bytes. The size is set to 0 if the method fails.
- LrfParams::decode(…): the object is not changed if the data is invalid.
- Null pointers are rejected by encode(…), decode(…), encodeCommand(…), encodeSetParamCommand(…) and decodeCommand(…).
- decodeCommand(…) returns -1 for command and param IDs outside of the LrfCommand and LrfParam enums.
- Serialization code of LrfParams made table driven (encoded data is not changed).
- Warning and security compiler and linker options added to CMake files, the MSVC linker option /MANIFEST:NO is set for MSVC only.
- CustomLrf example is thread-safe and validates values.
- Test application extended: deterministic, leaves no files, returns non-zero exit code on failure.
- Documentation updated.

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.
example -------------------- Folder with an example LRF controller.
    CMakeLists.txt --------- CMake file for example of LRF controller.
    CustomLrf.cpp ---------- C++ implementation file.
    CustomLrf.h ------------ Header with class declaration.
    CustomLrfVersion.h ----- Header file which includes class version.
    CustomLrfVersion.h.in -- CMake service file to generate version header.
test ----------------------- Folder with test application.
    CMakeLists.txt --------- CMake file for test application.
    main.cpp --------------- Source code file of test application.
src ------------------------ Folder with source code of the library.
    CMakeLists.txt --------- CMake file of the library.
    Lrf.cpp ---------------- C++ implementation file.
    Lrf.h ------------------ Header file which includes Lrf class declaration.
    LrfVersion.h ----------- Header file which includes version of the library.
    LrfVersion.h.in -------- CMake service file to generate version header.

Lrf interface class description

Lrf class declaration

Lrf interface class declared in Lrf.h file. Class declaration:

namespace rapidpixel
{
class Lrf
{
public:

    /// Class destructor.
    virtual ~Lrf();

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

    /// Open lrf controller.
    virtual bool openLrf(std::string initString) = 0;

    /// Init lrf controller by set of parameters.
    virtual bool initLrf(LrfParams& params) = 0;

    /// Close connection.
    virtual void closeLrf() = 0;

    /// Get lrf open status.
    virtual bool isLrfOpen() = 0;

    /// Get lrf connection status.
    virtual bool isLrfConnected() = 0;

    /// Set the lrf controller param.
    virtual bool setParam(LrfParam id, float value) = 0;

    /// Get the lrf controller param.
    virtual float getParam(LrfParam id) = 0;

    /// Get the lrf controller params.
    virtual void getParams(LrfParams& params) = 0;

    /// Execute lrf command.
    virtual bool executeCommand(LrfCommand id) = 0;

    /// Encode set param command.
    static void encodeSetParamCommand(
        uint8_t* data, int& size, LrfParam id, float value);

    /// Encode command.
    static void encodeCommand(uint8_t* data, int& size, LrfCommand id);

    /// Decode command.
    static int decodeCommand(
        uint8_t* data, int size, LrfParam& paramId,
        LrfCommand& commandId, float& value);

    /// Decode and execute command.
    virtual bool decodeAndExecuteCommand(uint8_t* data, int size) = 0;

protected:

    /// Default constructor. The class can be used as a base only.
    Lrf() = default;

    /// Copy constructor.
    Lrf(const Lrf& src) = default;

    /// Move constructor.
    Lrf(Lrf&& src) = default;

    /// Copy assignment.
    Lrf& operator= (const Lrf& src) = default;

    /// Move assignment.
    Lrf& operator= (Lrf&& src) = default;
};
}

getVersion method

The getVersion() method returns string of current class version. Particular LRF controller can have it’s own getVersion() method. Method declaration:

static std::string getVersion();

Method can be used without Lrf class instance:

std::cout << "Lrf class version: " << Lrf::getVersion() << std::endl;

Console output:

Lrf class version: 1.0.2

openLrf method

The openLrf(…) method initializes LRF controller. This method can be used instead of initLrf(…) method. LRF controller should establish connection to LRF hardware and should set default parameters. Method declaration:

virtual bool openLrf(std::string initString) = 0;
Parameter Value
initString Initialization string. LRF 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).

Returns: TRUE if the LRF controller initialized or FALSE if not.

initLrf method

The initLrf(…) method initializes LRF controller by set of parameters. This method can be used instead of openLrf(…) method (LrfParams class includes initString) when you need initialize LRF controller with not default parameters. LRF controller should establish connection to LRF hardware and should set necessary parameters according to given LrfParams. Method declaration:

virtual bool initLrf(LrfParams& params) = 0;
Parameter Value
params LrfParams class object. LrfParams class includes initString which used in openLrf(…) method.

Returns: TRUE if the LRF controller initialized or FALSE if not.

closeLrf method

The closeLrf() method closes connection to LRF. LRF controller should close connection to LRF hardware and should set connection and open flags to FALSE (see LrfParams class description). Method declaration:

virtual void closeLrf() = 0;

isLrfOpen method

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

virtual bool isLrfOpen() = 0;

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

isLrfConnected method

The isLrfConnected() method returns LRF connection status. Connection status shows if the LRF controller has data exchange with LRF equipment. For example, if LRF has serial port LRF controller connects to serial port (opens serial port file in OS) but LRF can be not active (no power). In this case connection status shows that LRF controller doesn’t have data exchange with LRF equipment (method will return FALSE). If LRF controller has data exchange with LRF equipment the method will return TRUE. If LRF controller not initialize the connection status always FALSE. Method declaration:

virtual bool isLrfConnected() = 0;

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

setParam method

The setParam(…) method sets new LRF parameters value. LRF controller must provide thread-safe setParam(…) method call. This means that the setParam(…) method can be safely called from any thread. Method declaration:

virtual bool setParam(LrfParam id, float value) = 0;
Parameter Description
id LRF parameter ID according to LrfParam enum.
value LRF parameter value. Value depends on parameter ID (see description of LrfParam enum).

Returns: TRUE if the parameter was set or FALSE if not.

getParam method

The getParam(…) method returns LRF parameter value. LRF controller must provide thread-safe getParam(…) method call. This means that the getParam(…) method can be safely called from any thread. Method declaration:

virtual float getParam(LrfParam id) = 0;
Parameter Description
id LRF parameter ID according to LrfParam enum.

Returns: parameter value or -1 of the parameters doesn’t exist (not supported) in LRF controller.

getParams method

The getParams(…) method designed to obtain all LRF parameters. LRF controller must provide thread-safe getParams(…) method call. This means that the getParams(…) method can be safely called from any thread. Method declaration:

virtual void getParams(LrfParams& params) = 0;
Parameter Description
params Reference to LrfParams object to store params.

executeCommand method

The executeCommand(…) method designed to execute LRF action command. LRF controller must provide thread-safe executeCommand(…) method call. This means that the executeCommand(…) method can be safely called from any thread. Method declaration:

virtual bool executeCommand(LrfCommand id) = 0;
Parameter Description
id LRF command ID according to LrfCommand enum.

Returns: TRUE is the command was executed (accepted by LRF controller) or FALSE if not.

encodeSetParamCommand method

The encodeSetParamCommand(…) static method designed to encode command to change any remote LRF parameter. To control a LRF 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 Lrf class contains static methods for encoding the control command. The Lrf 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, LrfParam id, float value);
Parameter Description
data Pointer to data buffer for encoded command. Must not be nullptr. Must have size >= 11.
size Size of encoded data. Will be 11 bytes (0 if data is nullptr: nothing is written in this case).
id Parameter ID according to LrfParam enum.
value Parameter value.

encodeSetParamCommand(…) is static and used without Lrf 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;
// Encode command.
Lrf::encodeSetParamCommand(data, size, LrfParam::OPERATING_MODE, 1);

encodeCommand method

The encodeCommand(…) static method designed to encode LRF action command (COMMAND). To control a LRF 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 Lrf class contains static methods for encoding the control command. The Lrf class provides two types of commands: a parameter change command (SET_PARAM) and an action command (COMMAND). encodeCommand(…) designed to encode COMMAND (action command). Method declaration:

static void encodeCommand(uint8_t* data, int& size, LrfCommand id);
Parameter Description
data Pointer to data buffer for encoded command. Must not be nullptr. Must have size >= 7.
size Size of encoded data. Will be 7 bytes (0 if data is nullptr: nothing is written in this case).
id Command ID according to LrfCommand enum.

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

// Buffer for encoded data.
uint8_t data[7];
// Size of encoded data.
int size = 0;
// Encode command.
Lrf::encodeCommand(data, size, LrfCommand::DISARM);

decodeCommand method

The decodeCommand(…) static method designed to decode command on LRF controller side. To control a LRF remotely, the developer has to develop his own protocol and according to it decode the command on LRF controller side. To simplify this, the Lrf interface class contains static method to decode input command (commands should be encoded by methods encodeSetParamCommand(…) or encodeCommand(…) methods). The Lrf 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, LrfParam& paramId, LrfCommand& commandId, float& value);
Parameter Description
data Pointer to input command. Must not be nullptr.
size Size of command. Must be 11 bytes for SET_PARAM and 7 bytes for COMMAND (a message of another size is an error).
paramId LRF parameter ID according to LrfParam enum. After decoding SET_PARAM command the method will return parameter ID.
commandId LRF command ID according to LrfCommand enum. After decoding COMMAND the method will return command ID.
value LRF parameter value after decoding SET_PARAM command.

Returns: 0 - in case decoding COMMAND (action command), 1 - in case decoding SET_PARAM command or -1 in case errors (data is nullptr, wrong size, version or command type, ID outside of the LrfCommand or LrfParam enum). The output arguments are changed only if the command is decoded.

decodeAndExecuteCommand method

The decodeAndExecuteCommand(…) method decodes and executes command on LRF controller side encoded by encodeSetParamCommand(…) or encodeCommand(…) methods. LRF controller must provide thread-safe decodeAndExecuteCommand(…) method call. This means that the decodeAndExecuteCommand(…) method can be safely called from any thread. Method declaration:

virtual bool decodeAndExecuteCommand(uint8_t* data, int size) = 0;
Parameter Description
data Pointer to input command.
size Size of command. Must be 11 bytes for SET_PARAM and 7 bytes for COMMAND (action command).

Returns: TRUE if command decoded (SET_PARAM or COMMAND) and executed (action command or set param command).

Data structures

LrfCommand enum

LrfCommand enum describes action LRF command. All commands must be supported by LRF controller. Enum declaration:

namespace rapidpixel
{
enum class LrfCommand
{
    /// Arm.
    ARM = 1,
    /// Disarm.
    DISARM,
    /// Measure distance once.
    MEASURE_DISTANCE_ONCE
};
}

Table 2 - LRF action commands description. Some commands may be unsupported by LRF controller.

Command Description
ARM Command to arm LRF.
DISARM Command to disarm LRF.
MEASURE_DISTANCE_ONCE Measure distance once.

LrfParam enum

LrfParam enum describes LRF parameters. Enum declaration:

namespace rapidpixel
{
enum class LrfParam
{
    /// [Read only] Current measured distance, meters.
    DISTANCE = 1,
    /// Time from last measurement, us.
    TIME_FROM_LAST_MEASUREMENT_US,
    /// Low power mode. Values depends on implementation. Default: 0 - OFF.
    LOW_POWER_MODE,
    /// Laser pointer mode: 0 - OFF, 1 - ON, 2 - ON timeout.
    POINTER_MODE,
    /// Pointer mode timeout, sec.
    POINTER_MODE_TIMEOUT_SEC,
    /// Arm mode: 0 - Disarmed, 1 - armed.
    ARM_MODE,
    /// Operating mode: 0 - OFF, 1 - Stand-by-mode, 2 - Normal mode.
    OPERATING_MODE,
    /// Continuous measuring mode: 0 - Stop, 1 - 0.5Hz, 2 - 1Hz, 3 - 3Hz,
    /// 4 - 5Hz, 5 - 10Hz.
    CONTINUOUS_MEASURING_MODE,
    /// Continuous mode timeout, sec.
    CONTINUOUS_MODE_TIMEOUT_SEC,
    /// Logging mode: 0 - Disabled, 1 - Console, 2 - File, 3 - Console and file.
    LOG_MODE,
    /// [Read only] Open status.
    IS_OPEN,
    /// [Read only] Connection status.
    IS_CONNECTED,
    /// Min gate distance, meters.
    MIN_GATE_DISTANCE,
    /// Max gate distance, meters.
    MAX_GATE_DISTANCE,
    /// Temperature, deg.
    TEMPERATURE_DEG,
    /// Custom parameter 1. Depends on implementation.
    CUSTOM_1,
    /// Custom parameter 2. Depends on implementation.
    CUSTOM_2,
    /// Custom parameter 3. Depends on implementation.
    CUSTOM_3
};
}

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

Parameter Access Description
DISTANCE read only Current measured distance, meters. LRF controller should keep this value until distance update.
TIME_FROM_LAST_MEASUREMENT_US read only Time from last measurement, microseconds. Used to control how old last measurement.
LOW_POWER_MODE read / write Low power mode. Values depends on LRF controller. Default: 0 - OFF.
POINTER_MODE read / write Laser pointer mode: 0 - OFF, 1 - ON, 2 - ON timeout (turn off automatically after timeout).
POINTER_MODE_TIMEOUT_SEC read / write Pointer mode timeout, sec.
ARM_MODE read / write Arm mode: 0 - Disarmed, 1 - armed.
OPERATING_MODE read / write Operating mode. Default values: 0 - OFF, 1 - Stand-by-mode, 2 - Normal mode.
CONTINUOUS_MEASURING_MODE read / write Continuous measuring mode. Default values: 0 - Stop, 1 - 0.5Hz, 2 - 1Hz, 3 - 3Hz, 4 - 5Hz, 5 - 10Hz.
CONTINUOUS_MODE_TIMEOUT_SEC read / write Continuous mode timeout, sec. Turn off measurements after timeout. If 0 - no timeout.
LOG_MODE read / write Logging mode: 0 - Disabled, 1 - Console, 2 - File, 3 - Console and file.
IS_OPEN read only Open status: 0 - not init (not open), 1 - open (init). Open status shows if the LRF controller initialized but doesn’t show if LRF controller has communication with LRF equipment. For example, if LRF has serial port LRF controller connects to serial port (opens serial port file in OS) but LRF can be not active (no power). In this case open status just shows that LRF controller has opened serial port.
IS_CONNECTED read only Connection status: 0 - no responses from LRF hardware, 1 - connected. Connection status shows if the LRF controller has data exchange with LRF equipment. For example, if LRF has serial port LRF controller connects to serial port (opens serial port file in OS) but LRF can be not active (no power). In this case connection status shows that LRF controller doesn’t have data exchange with LRF equipment. If LRF controller has data exchange with LRF equipment status will be 1. If LRF controller not initialize the connection status always 0.
MIN_GATE_DISTANCE read / write Min gate distance, meters. If parameter > 0 the LRF controller must ignore measured distance < MIN_GATE_DISTANCE.
MAX_GATE_DISTANCE read / write Max gate distance, meters. If parameter > 0 the LRF controller must ignore measured distance > MAX_GATE_DISTANCE.
TEMPERATURE_DEG read only LRF temperature, degree.
CUSTOM_1 read / write LRF custom parameter. Value depends on LRF controller. Custom parameters used when LRF equipment has specific unusual parameter.
CUSTOM_2 read / write LRF custom parameter. Value depends on LRF controller. Custom parameters used when LRF equipment has specific unusual parameter.
CUSTOM_3 read / write LRF custom parameter. Value depends on LRF controller. Custom parameters used when LRF equipment has specific unusual parameter.

LrfParams class description

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

LrfParams class declaration

LrfParams interface class declared in Lrf.h file. Class declaration:

namespace rapidpixel
{
class LrfParams
{
public:

    /// Initialization string. Format depends on implementation.
    std::string initString;
    /// Current measured distance, meters.
    float distance{0.0f};
    /// Time from last measurement, us.
    int timeFromLastMeasurementUs{0};
    /// Low power mode. Values depends on implementation. Default: 0 - OFF.
    int lowPowerMode{0};
    /// Laser pointer mode: 0 - OFF, 1 - ON, 2 - ON timeout.
    int pointerMode{0};
    /// Pointer mode timeout, sec.
    int pointerModeTimeoutSec{0};
    /// Arm mode: 0 - Disarmed, 1 - armed.
    int armMode{0};
    /// Operating mode: 0 - OFF, 1 - Stand-by-mode, 2 - Normal mode.
    int operatingMode{0};
    /// Continuous measuring mode: 0 - Stop, 1 - 0.5Hz, 2 - 1Hz, 3 - 3Hz,
    /// 4 - 5Hz, 5 - 10Hz.
    int continuousMeasuringMode{0};
    /// Continuous mode timeout, sec.
    int continuousModeTimeoutSec{0};
    /// Logging mode: 0 - Disabled, 1 - Console, 2 - File, 3 - Console and file.
    int logMode{0};
    /// Open status.
    bool isOpen{false};
    /// Connection status.
    bool isConnected{false};
    /// Min gate distance, meters.
    float minGateDistance{0};
    /// Max gate distance, meters.
    float maxGateDistance{0};
    /// Temperature, deg.
    float temperatureDeg{0.0f};
    /// Custom parameter 1. Depends on implementation.
    float custom1{0.0f};
    /// Custom parameter 2. Depends on implementation.
    float custom2{0.0f};
    /// Custom parameter 3. Depends on implementation.
    float custom3{0.0f};

    JSON_READABLE(LrfParams, initString, lowPowerMode, pointerModeTimeoutSec,
                  operatingMode, continuousModeTimeoutSec, logMode,
                  minGateDistance, maxGateDistance, custom1, custom2, custom3)

    /// Default constructor.
    LrfParams() = default;

    /// Copy constructor.
    LrfParams(const LrfParams& src) = default;

    /// operator =
    LrfParams& operator= (const LrfParams& src) = default;

    /// Encode (serialize) params.
    bool encode(uint8_t* data, int bufferSize, int& size,
                LrfParamsMask* mask = nullptr);

    /// Decode (deserialize) params.
    bool decode(uint8_t* data, int dataSize);
};
}

Table 4 - LrfParams class fields description (equivalent to LrfParam enum description).

Field type Description
initString string Initialization string. LRF 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). The same initialization string is used in openLrf(…) method.
distance float Current measured distance, meters. LRF controller should keep this value until distance update.
timeFromLastMeasurementUs int Time from last measurement, microseconds. Used to control how old last measurement.
lowPowerMode int Low power mode. Values depends on LRF controller. Default: 0 - OFF.
pointerMode int Laser pointer mode: 0 - OFF, 1 - ON, 2 - ON timeout (turn off automatically after timeout).
pointerModeTimeoutSec int Pointer mode timeout, sec.
armMode int Arm mode: 0 - Disarmed, 1 - armed.
operatingMode int Operating mode. Default values: 0 - OFF, 1 - Stand-by-mode, 2 - Normal mode.
continuousMeasuringMode int Continuous measuring mode. Default values: 0 - Stop, 1 - 0.5Hz, 2 - 1Hz, 3 - 3Hz, 4 - 5Hz, 5 - 10Hz.
continuousModeTimeoutSec int Continuous mode timeout, sec. Turn off measurements after timeout. If 0 - no timeout.
logMode int Logging mode: 0 - Disabled, 1 - Console, 2 - File, 3 - Console and file.
isOpen bool Open status: FALSE - not init (not open), TRUE - open (init). Open status shows if the LRF controller initialized but doesn’t show if LRF controller has communication with LRF equipment. For example, if LRF has serial port LRF controller connects to serial port (opens serial port file in OS) but LRF can be not active (no power). In this case open status just shows that LRF controller has opened serial port.
isConnected bool Connection status: FALSE - no responses from LRF hardware, TRUE - connected. Connection status shows if the LRF controller has data exchange with LRF equipment. For example, if LRF has serial port LRF controller connects to serial port (opens serial port file in OS) but LRF can be not active (no power). In this case connection status shows that LRF controller doesn’t have data exchange with LRF equipment. If LRF controller has data exchange with LRF equipment status will be TRUE. If LRF controller not initialize the connection status always FALSE.
minGateDistance float Min gate distance, meters. If parameter > 0 the LRF controller must ignore measured distance < minGateDistance.
maxGateDistance float Max gate distance, meters. If parameter > 0 the LRF controller must ignore measured distance > maxGateDistance.
temperatureDeg float LRF temperature, degree.
custom1 float LRF custom parameter. Value depends on LRF controller. Custom parameters used when LRF equipment has specific unusual parameter.
custom2 float LRF custom parameter. Value depends on LRF controller. Custom parameters used when LRF equipment has specific unusual parameter.
custom3 float LRF custom parameter. Value depends on LRF controller. Custom parameters used when LRF equipment has specific unusual parameter.

Note: LrfParams class fields listed in Table 4 must reflect params set/get by methods setParam(…) and getParam(…).

Serialize LRF params

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

bool encode(uint8_t* data, int bufferSize, int& size, LrfParamsMask* mask = nullptr);
Parameter Value
data Pointer to data buffer. Must not be nullptr.
size Size of encoded data. Set to 0 if the method returns FALSE.
bufferSize Data buffer size. Buffer size must be >= 72 bytes (the size of the data encoded with all fields).
mask Parameters mask - pointer to LrfParamsMask structure. LrfParamsMask (declared in Lrf.h file) determines flags for each field (parameter) declared in LrfParams 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 LrfParamsMask structure to FALSE. If the pointer is nullptr all fields are encoded.

Returns: TRUE if params encoded or FALSE if not (data is nullptr or the buffer is too small). If FALSE is returned nothing is written to the buffer.

LrfParamsMask structure declaration:

typedef struct LrfParamsMask
{
    bool distance{true};
    bool timeFromLastMeasurementUs{true};
    bool lowPowerMode{true};
    bool pointerMode{true};
    bool pointerModeTimeoutSec{true};
    bool armMode{true};
    bool operatingMode{true};
    bool continuousMeasuringMode{true};
    bool continuousModeTimeoutSec{true};
    bool logMode{true};
    bool isOpen{true};
    bool isConnected{true};
    bool minGateDistance{true};
    bool maxGateDistance{true};
    bool temperatureDeg{true};
    bool custom1{true};
    bool custom2{true};
    bool custom3{true};
} LrfParamsMask;

Example without parameters mask:

// Encode data.
LrfParams 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.
LrfParams in;
in.logMode = 3;

// Prepare mask.
LrfParamsMask 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 LRF params

LrfParams class provides method decode(…) to deserialize LRF params (fields of LrfParams class, see Table 4). Deserialization of LRF params necessary in case when you need to receive LRF params via communication channels. Method automatically recognizes which parameters were serialized by encode(…) method. Method doesn’t decode fields: initString (it is set to empty string). Parameters which were not serialized are set to zero (FALSE for flags). A flag is TRUE if its byte is not zero. Bytes after the last serialized parameter are ignored. The values of the parameters are not checked against any range. Method declaration:

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

Returns: TRUE if data decoded (deserialized) or FALSE if not (data is nullptr, wrong data type or version, the data is shorter than the mask requires). If FALSE is returned the object is not changed.

Example:

// Encode data.
LrfParams 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.
LrfParams 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

Lrf interface class library depends on ConfigReader library which provides method to read params from JSON file and to write params to JSON file. Only the fields listed in the JSON_READABLE macro (see LrfParams class declaration) are stored. The JSON document must contain all of these fields with values of the right types. If a field is missing or has a wrong type the get(…) method returns FALSE and the params are not changed. Example of writing and reading params to JSON file:

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

// Read params from file.
rapidpixel::ConfigReader outConfig;
if (!outConfig.readFromFile("TestLrfParams.json"))
{
    std::cout << "Can't open config file" << std::endl;
    return false;
}
// Parse params.
LrfParams out;
if (!outConfig.get(out, "LrfParams"))
{
    std::cout << "Can't read params from file" << std::endl;
    return false;
}

TestLrfParams.json will look like:

{
    "LrfParams": {
        "initString": "",
        "lowPowerMode": 0,
        "pointerModeTimeoutSec": 0,
        "operatingMode": 0,
        "continuousModeTimeoutSec": 0,
        "logMode": 0,
        "minGateDistance": 0.0,
        "maxGateDistance": 0.0,
        "custom1": 0.0,
        "custom2": 0.0,
        "custom3": 0.0
    }
}

Build and connect to your project

Build stand alone

The repository does not contain sub-repositories. The ConfigReader library which Lrf depends on must be cloned into the same folder as Lrf. The folder structure must be:

<work folder>
    Lrf
    ConfigReader

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

git clone <Lrf repository URL>
git clone <ConfigReader repository URL>
cd Lrf
mkdir build
cd build
cmake ..
make

On Windows use cmake --build . --config Release instead of make. If Lrf is the top-level CMake project, the main CMakeLists.txt file adds the folder ../ConfigReader before the library itself. If the folder does not exist CMake stops with an error.

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 Lrf is the top-level project).

Option Default Description
${PARENT}_LRF ON Build the library.
${PARENT}_LRF_TEST ON (stand alone), OFF (included in other project) Build the test application.
${PARENT}_LRF_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 Lrf as a sub-repository.
CMAKE_BUILD_TYPE Release (if not specified) Build type.

Connect to your project

If you want to connect Lrf library to your CMake project as source code you can make follow. Lrf does not add its dependencies when it is included in another project: your project must add the ConfigReader library by itself, before Lrf. If the ConfigReader library is not added the compilation stops with the error “ConfigReader.h: No such file or directory”. For example, if your repository has structure:

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

Create folder 3rdparty in your repository folder and copy Lrf and ConfigReader repository folders there. Structure of your repository after that:

CMakeLists.txt
src
    CMakeList.txt
    yourLib.h
    yourLib.cpp
3rdparty
    Lrf
    ConfigReader

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_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_LRF                             ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_LRF)
    SET(${PARENT}_LRF                                   ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_LRF_TEST                              OFF CACHE BOOL "" FORCE)
    SET(${PARENT}_LRF_EXAMPLE                           OFF CACHE BOOL "" FORCE)
endif()

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

if (${PARENT}_SUBMODULE_LRF)
    add_subdirectory(Lrf)
endif()

File 3rdparty/CMakeLists.txt adds folders ConfigReader and Lrf (in this order) to your project and excludes test applications and examples (Lrf class test application and example of custom LRF class implementation) from compiling (by default test applications and examples are excluded from compiling if the libraries are included as sub-repositories). Structure of your repository will be:

CMakeLists.txt
src
    CMakeList.txt
    yourLib.h
    yourLib.cpp
3rdparty
    CMakeLists.txt
    Lrf
    ConfigReader

Next you need include folder 3rdparty in main CMakeLists.txt file of your repository. Add string at the end of your main CMakeLists.txt:

add_subdirectory(3rdparty)

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

target_link_libraries(${PROJECT_NAME} Lrf)

Done!

How to make custom implementation

The Lrf class provides only an interface, data structures, and methods for encoding and decoding commands and params. To create your own implementation of the LRF controller, you must include the Lrf repository in your project (see Connect to your project section). The catalogue example (see Library files section) includes an example of the design of the custom LRF controller. You must implement all the methods of the Lrf interface class. The methods setParam(…), getParam(…), getParams(…), executeCommand(…) and decodeAndExecuteCommand(…) must be thread-safe: the example protects the params by a mutex. The example checks the values received from outside (the param value, the command ID, the initialization params) and rejects values out of the range of the param. Custom LRF class declaration:

namespace rapidpixel
{
/**
 * @brief Custom lrf controller.
 */
class CustomLrf: public Lrf
{
public:

    /// Class constructor.
    CustomLrf();

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

    /// Copy and move are deleted: the class owns a mutex.
    CustomLrf(const CustomLrf&) = delete;
    CustomLrf(CustomLrf&&) = delete;
    CustomLrf& operator= (const CustomLrf&) = delete;
    CustomLrf& operator= (CustomLrf&&) = delete;

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

    /// Open lrf controller.
    bool openLrf(std::string initString) override;

    /// Init lrf controller by structure.
    bool initLrf(LrfParams& params) override;

    /// Close connection.
    void closeLrf() override;

    /// Get lrf open status.
    bool isLrfOpen() override;

    /// Get lrf connection status.
    bool isLrfConnected() override;

    /// Set the lrf controller param.
    bool setParam(LrfParam id, float value) override;

    /// Get the lrf controller param.
    float getParam(LrfParam id) override;

    /// Get the lrf controller params.
    void getParams(LrfParams& params) override;

    /// Execute lrf command.
    bool executeCommand(LrfCommand id) override;

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

private:

    /// Parameters. Protected by m_mutex.
    LrfParams m_params;
    /// Mutex to protect m_params.
    std::mutex m_mutex;
};
}

Portability

The encoded data of the LrfParams class and the encoded commands store int and float values as raw 4-byte values in the byte order of the host. The sizes of int and float (4 bytes) and the IEEE 754 format of float are checked at compile time. The library has been built and run with GCC 11 and GCC 12 on x86-64 and with the GCC 11 cross compiler for AArch64 (the test application was run under an emulator). Both processor families are little-endian.


Table of contents