bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
vector_message.h
Go to the documentation of this file.
1//
2// Created by alex on 11/30/25.
3//
4
5#ifndef BITSIM_SENSORS_MESSAGES_VECTOR_MESSAGE_H
6#define BITSIM_SENSORS_MESSAGES_VECTOR_MESSAGE_H
7
9
10#include <locale>
11#include <optional>
12#include <string>
13#include <vector>
14
15namespace bitsim
16{
17namespace sensors
18{
19template <typename T> struct EigenVectorMessage
20{
22 static std::optional<EigenVectorMessage<T>> parse(const std::string &msg);
23};
24
25template <typename T>
26std::optional<EigenVectorMessage<T>> EigenVectorMessage<T>::parse(const std::string &msg)
27{
28 // --- Trim whitespace ---
29 auto trim = [](const std::string &s)
30 {
31 size_t start = 0;
32 while (start < s.size() && std::isspace(s[start]))
33 start++;
34 size_t end = s.size();
35 while (end > start && std::isspace(s[end - 1]))
36 end--;
37 return s.substr(start, end - start);
38 };
39
40 std::string s = trim(msg);
41
42 if (s.empty() || s.front() != '[' || s.back() != ']')
43 return std::nullopt;
44
45 // Remove '[' and ']'
46 s = s.substr(1, s.size() - 2);
47
48 std::vector<T> values;
49 std::stringstream ss(s);
50 std::string item;
51
52 while (std::getline(ss, item, ','))
53 {
54 item = trim(item);
55 if (item.empty())
56 return std::nullopt;
57
58 std::stringstream item_ss(item);
59 T value;
60
61 if (!(item_ss >> value)) // Parsing failed
62 return std::nullopt;
63
64 values.push_back(value);
65 }
66
68 result.message = DynVec<T>::Zero(values.size());
69 for (size_t i = 0; i < values.size(); ++i)
70 result.message[i] = values[i];
71 return result;
72}
73
74} // namespace sensors
75} // namespace bitsim
76
77#endif // BITSIM_SENSORS_MESSAGES_VECTOR_MESSAGE_H
The basic types of bitsim. Code outside this file names Eigen's matrix and vector types only through ...
Definition infrared_line_follower.h:9
Definition dc_motor_backend_base.h:9
Eigen::RowVectorX< T > DynVec
Dynamically sized row vector.
Definition bitsim_types.h:101
Definition vector_message.h:20
static std::optional< EigenVectorMessage< T > > parse(const std::string &msg)
Definition vector_message.h:26
DynVec< T > message
Definition vector_message.h:21