Veethree D7 SDK
Loading...
Searching...
No Matches
Comms library examples

Serial Examples

The example code in cli-serial.cpp demonstrates how to configure, read and write from a serial port.

Test harness

This example uses RS232, which corresponds to pins 10 (RS232_TX) and 9 (RS232_RX) on the AMPSEAL 23-pin connector on the D7. Simply connect pin 10 to pin 9, so that RS232 is configured in a loopback.

CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(
serial-app
VERSION 0.1
LANGUAGES CXX)
# Set C++ standard to C++20
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 20)
# Project name
set(APPNAME cli-serial-app)
# Find VSDK packages
find_package(vsdk REQUIRED CONFIG COMPONENTS comms utils)
# Add executable and link against VSDK libraries
add_executable(${APPNAME} cli-serial.cpp)
target_link_libraries(${APPNAME} PRIVATE vsdk::comms vsdk::utils)
## Deploy to target from Qt Creator
include(GNUInstallDirs)
install(TARGETS ${APPNAME}
BUNDLE DESTINATION .
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
@ comms
Comms module.
Definition log.h:41
Any entities that belong to the comms library.
Definition can_adapter.h:12
Any entities that belong to the utils library.
Any entities that belong to the Veethree SDK libraries.
Definition can_adapter.h:12
cli-serial.cpp
#include <array>
#include <span>
#include <thread>
#include <fmt/core.h>
#include <fmt/format.h>
using namespace vsdk::comms;
using namespace std::chrono_literals;
int main() {
//
// the very same is applicable for RS422 or RS485,
// just use port 0 and the port_mode you need
//
port_attributes rs232_attr;
rs232_attr.port = port_alias::port1;
rs232_attr.parity = port_parity::none;
//
// In this example, we are using a receive function that will be
// called when there is activity in the port
//
size_t frame_counter{};
auto rs232_receive = [&frame_counter](std::span<uint8_t> buf) {
size_t counter{};
for (auto& data : buf) {
if (counter % 8 == 0)
fmt::print("\nreceived {}: ", frame_counter++);
fmt::print("{:#04x} ", data);
counter++;
}
};
//
// Create the serial port and pass its attributes and receive function
//
serial_port rs232(rs232_attr, rs232_receive);
// drain and flush your port, it depends on your needs
rs232.drain();
// example data to be written to the port
// loop to control if all data has been written
for (uint32_t i{}; i < 128; ++i) {
std::array<uint8_t, 8> rs232_frame{ 1, 2, 3, 4, 5, 6, 7, 8 };
ssize_t written{};
while (written < rs232_frame.size()) {
std::span<uint8_t> buf{ rs232_frame.data() + written, rs232_frame.size() - written };
auto ret = rs232.write(buf);
if (ret == -1) {
// handle error properly
break;
}
fmt::println("Sent {} byte(s)", ret);
written += ret;
}
}
// allow some time for the receive function to be called
// this would be your application loop
std::this_thread::sleep_for(3s);
return 0;
}
The serial_port class.
Definition serial_port.h:72
Add include this file to your file so you have access to fmtlib header-only implementation.
@ bits1
One stop bit.
Definition serial_port_common.h:91
@ rs232
RS232 mode.
Definition serial_port_common.h:155
@ uart115200
115200 baud
Definition serial_port_common.h:58
@ both
Flush both input and output buffers.
Definition serial_port_common.h:121
@ none
No parity.
Definition serial_port_common.h:75
@ bits8
8 data bits
Definition serial_port_common.h:107
@ port1
RS232 port.
Definition serial_port_common.h:138
serial_port interface
Serial Port Common.
Structure representing serial port configuration attributes.
Definition serial_port_common.h:177
port_alias port
The port alias.
Definition serial_port_common.h:178
port_data_bits data_bits
The number of data bits.
Definition serial_port_common.h:182
port_mode uart_mode
The UART mode.
Definition serial_port_common.h:183
port_stop_bits stop_bits
The number of stop bits.
Definition serial_port_common.h:181
port_baud_rate baud_rate
The baud rate.
Definition serial_port_common.h:179
port_parity parity
The parity setting.
Definition serial_port_common.h:180

CAN Examples

The example code in cli-can.cpp demonstrates how to being a CAN port up or down, configure it, open a socket on it and send/receive CAN frames.

NOTE: If you want to test this example on Linux but don't have physical CAN interfaces, you can create virtual CAN interfaces for testing:

# Load the virtual CAN kernel module
sudo modprobe vcan
# Create virtual CAN interfaces
sudo ip link add dev can0 type vcan
sudo ip link add dev can1 type vcan
# Bring the interfaces up
sudo ip link set up can0
sudo ip link set up can1

Test harness on the target device

To run this example on the device, you will need to connect the CAN port on pins 16 and 17 of the AMPSEAL 23 connector to the same bus as the CAN port on the M12 A-coded connector.

CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(
can-app
VERSION 0.1
LANGUAGES CXX)
# Set C++ standard to C++20
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 20)
# Project name
set(APPNAME cli-can-app)
# Find VSDK packages
find_package(vsdk REQUIRED CONFIG COMPONENTS comms)
# Add executable and link against VSDK libraries
add_executable(${APPNAME} cli-can.cpp)
target_link_libraries(${APPNAME} PRIVATE vsdk::comms)
## Deploy to target from Qt Creator
include(GNUInstallDirs)
install(TARGETS ${APPNAME}
BUNDLE DESTINATION .
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
cli-can.cpp
#include <latch>
#include <thread>
// This example uses 2 threads:
// - one to send a CAN frame on can0
// - one to receive a CAN frame on can1
using namespace std::chrono_literals;
using namespace vsdk::comms;
bool check_can_interfaces()
{
std::vector<std::string> interfaces = { "can0", "can1" };
for (const auto& interface : interfaces) {
std::string path = "/sys/class/net/" + interface;
fmt::println("CAN interface '{}' does not exist", interface);
return false;
}
}
fmt::println("All required CAN interfaces (can0, can1) are available");
return true;
}
void sender_thread(std::latch& bus_active, std::latch& finished)
{
// An instance of vsdk::comms::can_adapter represents a specific CAN port on the D7.
// The class allows bringing the port up, down, configuring the port's CAN settings
// (bitrate, sample point, controller mode, etc) and querying the port's current configuration.
can_adapter can0("can0");
// The class also offers convenience methods for starting with a default bitrate, getting/setting the birate and
// getting the CAN bus's current state.
//
// All convenience methods just wrap calls to can_adapter::get_config/set_config.
// The can_adapter::set_config method behaves the same way as using `ip link set <interface name> type can <options>`,
// meaning the same checks on the given settings will be done.
can0.start(bitrate_125k);
bus_active.arrive_and_wait();
if (can0.get_bus_state() != can_status::error_active) {
fmt::println("Bus is not active for adapter {}", can0.name());
} else {
// The can_socket class is a OOP-style wrapper for SocketCAN sockets.
// Internally uses a shared_ptr to maintain the socket open for as long as the instances is alive.
// This means that copying and moving an instance of can_socket keeps the underlying socket open
// until the last reference goes out of scope.
can_socket socket;
// Bind the socket to an adapter
socket.bind(can0);
// Allow time for the receiver thread to start listening
std::this_thread::sleep_for(100ms);
// Construct a CAN frame
std::string msg = "hello";
// NAME 0, SA 40, PGN 02300, data bytes b'hello'
can_msg_frame frame{ .can_id = 2552495936, .len = (uint8_t) msg.length() };
std::memcpy(frame.data, msg.data(), std::min(sizeof(frame.data), msg.length()));
// Send the frame on the socket
if (auto err = socket.send(frame); err == std::errc{}) {
fmt::println("Sent {}", msg);
} else {
fmt::println("Failed to send CAN frame: {}", vsdk::utils::errno_string((int) err));
}
}
finished.count_down();
}
void receiver_thread(std::latch& bus_active, std::latch& finished)
{
// See sender_thread for in-depth explanation on can_adapter
can_adapter can1("can1");
can1.start(bitrate_125k);
bus_active.arrive_and_wait();
if (can1.get_bus_state() != can_status::error_active) {
fmt::println("Bus is not active for adapter {}", can1.name());
} else {
// See sender_thread for in-depth explanation on setting up `can_socket`s.
can_socket socket;
socket.bind(can1);
// Receiving CAN frame with a timeout.
// If the timeout is std::chrono::milliseconds::zero(), the call will block indefinitely.
// There is also the option to make the socket non-blocking by calling
// socket.set_nonblocking();
can_msg_frame frame{};
if (auto err = socket.receive(frame, 200ms); err.recv_err == std::errc{}) {
std::string received_msg{ (char*) frame.data, (char*) frame.data + frame.len };
fmt::println("Received: {}", received_msg);
} else {
fmt::println("Failed to receive CAN frame: {}",
vsdk::utils::errno_string((int) err.recv_err));
}
}
finished.count_down();
}
int main()
{
#ifdef __linux__
if (!check_can_interfaces()) {
fmt::println("Required CAN interfaces are not available");
return 1;
}
#endif
std::latch bus_active{ 2 };
std::latch finished{ 2 };
std::jthread sender(sender_thread, std::ref(bus_active), std::ref(finished));
std::jthread receiver(receiver_thread, std::ref(bus_active), std::ref(finished));
finished.wait();
fmt::println("Done");
}
CAN Adapter.
CAN Socket.
The CAN interface setup class.
Definition can_adapter.h:48
Convenience wrapper class around a CAN socket.
Definition can_socket.h:22
std::errc bind(const can_adapter &adapter)
Open the socket and bind to an adapter.
receive_result receive(can_msg_frame &frame, std::chrono::milliseconds timeout=std::chrono::milliseconds::zero()) const
Receive a CAN frame.
std::errc send(const can_msg_frame &frame) const
Send a CAN frame.
Utilities for file manipulation.
constexpr uint32_t bitrate_125k
Common CAN bitrates.
Definition can_adapter_interface.h:27
@ error_active
RX/TX error count < 96.
Definition can_common.h:47
std::string errno_string(int err)
Wrapper for strerror that returns a std::string.
bool file_exists(const std::string &path)
Utility to check if a path exists. Same semantics as std::filesystem::exists, but won't do character ...
Definition file_utils.h:113
CAN frame structure.
Definition can_common.h:32
uint8_t len
Frame payload length.
Definition can_common.h:34
The interface struct.
Definition network_manager.h:46
std::errc recv_err
The error code for receving the CAN frame.
Definition can_socket_interface.h:27
syscall wrapper interface.

Networking Examples

The example code in cli-network.cpp demonstrates how to retrieve information about networking interfaces.

CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(
network-app
VERSION 0.1
LANGUAGES CXX)
# Set C++ standard to C++20
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 20)
# Project name
set(APPNAME cli-network-app)
# Find VSDK packages
find_package(vsdk REQUIRED CONFIG COMPONENTS comms utils)
# Add executable and link against VSDK libraries
add_executable(${APPNAME} cli-network.cpp)
target_link_libraries(${APPNAME} PRIVATE vsdk::comms vsdk::utils)
# Needed to demonstrate instantiating a network interface by name
# On the device, eth0 is the default ethernet interface name.
# On desktop distributions, that may be different.
if (UNIX AND CMAKE_CROSSCOMPILING)
target_compile_definitions(${APPNAME} PUBLIC TARGET_BUILD=1)
endif()
## Deploy to target from Qt Creator
include(GNUInstallDirs)
install(TARGETS ${APPNAME}
BUNDLE DESTINATION .
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
@ network
Network module.
Definition log.h:40
cli-network.cpp
#include <fmt/core.h>
#include <fmt/format.h>
using namespace vsdk::comms;
using namespace vsdk;
namespace {
void print_info(interface const& iface)
{
utils::print("INTERFACE: {}\n", iface.name);
utils::print("\tIP: {}\n", iface.ip);
utils::print("\tHWADDR: {}\n", iface.hwaddr);
utils::print("\tTYPE: {}\n", iface.type);
utils::print("\tSTATUS: {}\n", iface.status);
}
} // anonymous namespace
int main()
{
try {
#ifdef TARGET_BUILD
//
// Get information about a single interface
//
utils::print("{:*<78}\n", "SINGLE INTERFACE ");
auto eth0 = network_manager::get_interface("eth0");
print_info(eth0);
#endif
//
// List all interfaces
//
utils::print("{:*<78}\n", "ALL INTERFACES ");
auto interfaces = network_manager::get_interfaces();
for (const auto& iface : interfaces) {
print_info(iface);
}
} catch (std::exception const& e) {
utils::print("exception: {}\n", e.what());
return 1;
}
return 0;
}
static std::vector< interface > get_interfaces()
Return all the network interfaces available for the target.
static interface get_interface(std::string_view iface)
Return the interface information identified by iface.
void print(fmt::format_string< Args... > fmt, Args &&...args) noexcept
Exception-safe fmt::print wrapper.
Definition fmt_wrapper.h:26
The network_manager interface.
interface_type type
The interface type.
Definition network_manager.h:51
std::string name
The interface name.
Definition network_manager.h:47
interface_status status
The interface status.
Definition network_manager.h:50
std::string ip
The interface IP address if available or applicable.
Definition network_manager.h:48
std::string hwaddr
The interface HW address if applicable.
Definition network_manager.h:49