Skip to content

Commit 351cf44

Browse files
committed
Added result<> ostream inserter. Updated CAN example with new canbusfdtime.cpp
1 parent eb8fbd4 commit 351cf44

11 files changed

Lines changed: 210 additions & 31 deletions

File tree

‎examples/canbus/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838

3939
set(EXECUTABLES
4040
canbustime
41+
canbusfdtime
4142
canbusrecv
4243
canbusrecvts
4344
canbusfdrecv

‎examples/canbus/canbusfdrecv.cpp‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ int main(int argc, char* argv[]) {
7979
if (hasFilter) {
8080
can_filter filter{canID, CAN_SFF_MASK};
8181
if (auto res = sock.set_filters(&filter, 1); !res) {
82-
cerr << "Error setting filter: " << res.error().message() << endl;
82+
cerr << "Error setting filter: " << res << endl;
8383
return 1;
8484
}
8585
}
@@ -96,7 +96,7 @@ int main(int argc, char* argv[]) {
9696
while (true) {
9797
auto res = sock.recv_any();
9898
if (!res) {
99-
cerr << "Error receiving frame: " << res.error().message() << endl;
99+
cerr << "Error receiving frame: " << res << endl;
100100
break;
101101
}
102102

‎examples/canbus/canbusfdtime.cpp‎

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
// canbusfdtime.cpp
2+
//
3+
// Linux SocketCAN FD writer example.
4+
//
5+
// This writes the current time to the CAN bus 10 times per second as a
6+
// 12-byte CAN FD frame with nanosecond resolution. The payload format is:
7+
//
8+
// Bytes 0-7: int64_t seconds since the Unix epoch (big-endian host order)
9+
// Bytes 8-11: uint32_t nanosecond fraction
10+
//
11+
// This is a simple (though not overly precise) way to synchronize the time
12+
// for nodes on the CAN bus.
13+
//
14+
// --------------------------------------------------------------------------
15+
// This file is part of the "sockpp" C++ socket library.
16+
//
17+
// Copyright (c) 2026 Frank Pagliughi
18+
// All rights reserved.
19+
//
20+
// Redistribution and use in source and binary forms, with or without
21+
// modification, are permitted provided that the following conditions are
22+
// met:
23+
//
24+
// 1. Redistributions of source code must retain the above copyright notice,
25+
// this list of conditions and the following disclaimer.
26+
//
27+
// 2. Redistributions in binary form must reproduce the above copyright
28+
// notice, this list of conditions and the following disclaimer in the
29+
// documentation and/or other materials provided with the distribution.
30+
//
31+
// 3. Neither the name of the copyright holder nor the names of its
32+
// contributors may be used to endorse or promote products derived from this
33+
// software without specific prior written permission.
34+
//
35+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
36+
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
37+
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
38+
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
39+
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
40+
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
41+
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
42+
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
43+
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
44+
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
45+
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
46+
// --------------------------------------------------------------------------
47+
48+
#include <time.h>
49+
50+
#include <chrono>
51+
#include <cstdint>
52+
#include <cstring>
53+
#include <iostream>
54+
#include <string>
55+
#include <thread>
56+
57+
#include "sockpp/canbus/canbus_socket.h"
58+
#include "sockpp/version.h"
59+
60+
using namespace std;
61+
62+
// The clock to use to pace the app.
63+
using sysclock = chrono::system_clock;
64+
65+
// --------------------------------------------------------------------------
66+
67+
int main(int argc, char* argv[]) {
68+
cout << "Sample SocketCAN FD time writer for 'sockpp' " << sockpp::SOCKPP_VERSION << endl;
69+
70+
string canIface = (argc > 1) ? argv[1] : "can0";
71+
canid_t canID = (argc > 2) ? canid_t(strtoul(argv[2], nullptr, 0)) : 0x20;
72+
73+
sockpp::initialize();
74+
75+
error_code ec{};
76+
sockpp::canbus_address addr(canIface, ec);
77+
78+
if (ec) {
79+
cerr << "Error finding the CAN interface: " << canIface << "\n\t" << ec.message()
80+
<< endl;
81+
return 1;
82+
}
83+
84+
sockpp::canbusfd_socket sock(addr, ec);
85+
if (ec) {
86+
cerr << "Error opening CAN FD socket on " << canIface << "\n\t" << ec.message()
87+
<< endl;
88+
return 1;
89+
}
90+
91+
cout << "Created CAN FD socket on " << sock.address() << endl;
92+
93+
// Schedule the first send at the next 100ms boundary.
94+
auto next = sysclock::now();
95+
96+
while (true) {
97+
next += chrono::milliseconds(100);
98+
this_thread::sleep_until(next);
99+
100+
// Get the current time with nanosecond resolution
101+
timespec ts{};
102+
clock_gettime(CLOCK_REALTIME, &ts);
103+
104+
// Pack into a 12-byte payload: 8-byte int64_t seconds + 4-byte uint32_t ns
105+
int64_t secs = int64_t(ts.tv_sec);
106+
uint32_t nsec = uint32_t(ts.tv_nsec);
107+
108+
uint8_t payload[12];
109+
memcpy(payload, &secs, sizeof(secs));
110+
memcpy(payload + sizeof(secs), &nsec, sizeof(nsec));
111+
112+
sockpp::canbusfd_frame frame{canID, payload, sizeof(payload)};
113+
if (auto res = sock.send(frame); !res) {
114+
cerr << "Error sending frame: " << res << endl;
115+
return 1;
116+
}
117+
}
118+
119+
return 0;
120+
}

‎examples/canbus/canbusrecv.cpp‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ int main(int argc, char* argv[]) {
7575
if (hasFilter) {
7676
can_filter filter{canID, CAN_SFF_MASK};
7777
if (auto res = sock.set_filters(&filter, 1); !res) {
78-
cerr << "Error setting filter: " << res.error().message() << endl;
78+
cerr << "Error setting filter: " << res << endl;
7979
return 1;
8080
}
8181
}
@@ -91,7 +91,7 @@ int main(int argc, char* argv[]) {
9191
while (true) {
9292
auto res = sock.recv();
9393
if (!res) {
94-
cerr << "Error receiving frame: " << res.error().message() << endl;
94+
cerr << "Error receiving frame: " << res << endl;
9595
break;
9696
}
9797

‎examples/canbus/canbusrecvts.cpp‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,7 @@ static double to_secs(system_clock::time_point tp) {
7070
// Prints the frame ID, length, and data bytes to stdout.
7171
// Assumes hex/uppercase/setfill('0') are already set on cout.
7272
static void print_frame(const sockpp::canbus_frame& frame) {
73-
cout << setw(3) << frame.id_value() << " [" << dec << frame.length() << "] "
74-
<< hex;
73+
cout << setw(3) << frame.id_value() << " [" << dec << frame.length() << "] " << hex;
7574
for (uint8_t i = 0; i < frame.len; ++i) {
7675
cout << setw(2) << unsigned(frame.data[i]) << " ";
7776
}
@@ -111,7 +110,7 @@ int main(int argc, char* argv[]) {
111110
if (hasFilter) {
112111
can_filter filter{canID, CAN_SFF_MASK};
113112
if (auto res = sock.set_filters(&filter, 1); !res) {
114-
cerr << "\nError setting filter: " << res.error().message() << endl;
113+
cerr << "\nError setting filter: " << res << endl;
115114
return 1;
116115
}
117116
cout << " for CAN ID 0x" << hex << uppercase << canID;
@@ -122,7 +121,7 @@ int main(int argc, char* argv[]) {
122121
// Enable software SO_TIMESTAMPNS
123122

124123
if (auto res = sock.set_recv_timestamp(); !res) {
125-
cerr << "Error enabling SO_TIMESTAMPNS: " << res.error().message() << "\n";
124+
cerr << "Error enabling SO_TIMESTAMPNS: " << res << "\n";
126125
return 1;
127126
}
128127

@@ -135,7 +134,7 @@ int main(int argc, char* argv[]) {
135134
SOF_TIMESTAMPING_RX_HARDWARE | SOF_TIMESTAMPING_RAW_HARDWARE
136135
);
137136
!res) {
138-
cerr << "Error enabling SO_TIMESTAMPING: " << res.error().message() << "\n";
137+
cerr << "Error enabling SO_TIMESTAMPING: " << res << "\n";
139138
return 1;
140139
}
141140
}
@@ -152,7 +151,7 @@ int main(int argc, char* argv[]) {
152151
while (true) {
153152
auto res = sock.recv_with_timestamps();
154153
if (!res) {
155-
cerr << "Error receiving frame: " << res.error().message() << "\n";
154+
cerr << "Error receiving frame: " << res << "\n";
156155
break;
157156
}
158157
// Here ts is a `canbus_timestamps` struct.
@@ -170,7 +169,7 @@ int main(int argc, char* argv[]) {
170169
while (true) {
171170
auto res = sock.recv_with_timestamp();
172171
if (!res) {
173-
cerr << "Error receiving frame: " << res.error().message() << "\n";
172+
cerr << "Error receiving frame: " << res << "\n";
174173
break;
175174
}
176175
const auto& [frame, ts] = res.value();

‎examples/canbus/canbustime.cpp‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1-
// cantime.cpp
1+
// canbustime.cpp
22
//
3-
// Linux SoxketCAN writer example.
3+
// Linux SocketCAN writer example.
44
//
5-
// This writes the 1-sec, 32-bit, Linux time_t value to the CAN bus each
5+
// This writes the 1-sec, 64-bit, Linux time_t value to the CAN bus each
66
// time it ticks. This is a simple (though not overly precise) way to
7-
// synchronize the time for nodes on the bus
7+
// synchronize the time for nodes on the bus.
88
//
99
// --------------------------------------------------------------------------
1010
// This file is part of the "sockpp" C++ socket library.
1111
//
12-
// Copyright (c) 2021 Frank Pagliughi
12+
// Copyright (c) 2021-2026 Frank Pagliughi
1313
// All rights reserved.
1414
//
1515
// Redistribution and use in source and binary forms, with or without
@@ -44,6 +44,7 @@
4444
#include <sys/ioctl.h>
4545

4646
#include <chrono>
47+
#include <cstdint>
4748
#include <iostream>
4849
#include <string>
4950
#include <thread>
@@ -93,8 +94,8 @@ int main(int argc, char* argv[]) {
9394
// Re-read the time in case we fell behind
9495
t = sysclock::to_time_t(sysclock::now());
9596

96-
// Write the time to the CAN bus as a 32-bit int
97-
auto nt = uint32_t(t);
97+
// Write the time to the CAN bus as a 64-bit int
98+
auto nt = int64_t(t);
9899

99100
sockpp::canbus_frame frame{canID, &nt, sizeof(nt)};
100101
sock.send(frame);

‎examples/tcp/tcp6echo.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ int main(int argc, char* argv[]) {
6565

6666
if (!addrRes) {
6767
cerr << "Error resolving address for '" << host << "':\n\t"
68-
<< addrRes.error().message() << endl;
68+
<< addrRes << endl;
6969
return 1;
7070
}
7171

‎include/sockpp/canbus/canbus_frame.h‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -162,9 +162,7 @@ class canbus_frame : public ::can_frame
162162
* Gets the length of data (number of bytes) as a size_t.
163163
* @return The number of valid data bytes.
164164
*/
165-
size_t length() const {
166-
return size_t(this->len);
167-
}
165+
size_t length() const { return size_t(this->len); }
168166
#if __cplusplus >= 202002L
169167
/**
170168
* Returns the payload as a span of bytes.

‎include/sockpp/result.h‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,6 @@ struct none
5656
{
5757
};
5858

59-
#if 0
6059
/**
6160
* Writes out a none value.
6261
* @param os The output stream.
@@ -66,7 +65,6 @@ inline std::ostream& operator<<(std::ostream& os, const none&) {
6665
os << "<none>";
6766
return os;
6867
}
69-
#endif
7068

7169
/////////////////////////////////////////////////////////////////////////////
7270

@@ -566,14 +564,26 @@ bool operator!=(const errc& err, const result<T>& res) noexcept {
566564
return res.error() != err;
567565
}
568566

569-
#if 0
567+
namespace detail {
568+
/// @cond INTERNAL
569+
// Detects whether T supports `ostream << T`.
570+
template <typename T, typename = void>
571+
struct is_ostream_insertable : std::false_type {};
572+
573+
template <typename T>
574+
struct is_ostream_insertable<
575+
T,
576+
std::void_t<decltype(std::declval<std::ostream&>() << std::declval<const T&>())>>
577+
: std::true_type {};
578+
/// @endcond
579+
} // namespace detail
580+
570581
/**
571582
* Writes out the result.
572583
*
573-
* For a successful operation, writes out the result value. For a failed
574-
* operation, writes out the error message.
575-
*
576-
* This requires type T to have a stream inserter.
584+
* For a successful operation whose value type supports `operator<<`, writes
585+
* the value; otherwise writes `<ok>`. For a failed operation, writes the
586+
* error message.
577587
*
578588
* @param os The output stream.
579589
* @param res The result to output.
@@ -582,14 +592,16 @@ bool operator!=(const errc& err, const result<T>& res) noexcept {
582592
template <typename T>
583593
std::ostream& operator<<(std::ostream& os, const result<T>& res) {
584594
if (res.is_ok()) {
585-
os << res.value();
595+
if constexpr (detail::is_ostream_insertable<T>::value)
596+
os << res.value();
597+
else
598+
os << "<ok>";
586599
}
587600
else {
588601
os << res.error_message();
589602
}
590603
return os;
591604
}
592-
#endif
593605

594606
/////////////////////////////////////////////////////////////////////////////
595607
} // namespace sockpp

‎scripts/canfdup.sh‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#!/bin/bash
2+
#
3+
# canfdup.sh
4+
#
5+
# Brings up a Linux SocketCAN FD (CANbus FD) interface.
6+
#
7+
# USAGE: canfdup.sh [iface] [bitrate] [data_bitrate]
8+
#
9+
10+
if [[ $EUID -ne 0 ]]; then
11+
echo "This script must be run as root"
12+
exit 1
13+
fi
14+
15+
IFACE=can0
16+
BITRATE=500000
17+
DATABITRATE=2000000
18+
19+
[ -n "$1" ] && IFACE=$1
20+
[ -n "$2" ] && BITRATE=$2
21+
[ -n "$3" ] && DATABITRATE=$3
22+
23+
ip link set ${IFACE} up type can bitrate ${BITRATE} dbitrate ${DATABITRATE} fd on && \
24+
printf "%s brought up at bitrate %s\n" "${IFACE}" "${BITRATE}"
25+

0 commit comments

Comments
 (0)