-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcansocket.hpp
More file actions
2270 lines (1916 loc) · 79.4 KB
/
cansocket.hpp
File metadata and controls
2270 lines (1916 loc) · 79.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2025 TierOne Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <array>
#include <atomic>
#include <cerrno>
#include <chrono>
#include <cstring> // for strerror
#include <fcntl.h>
#include <iomanip>
#include <iostream>
#include <memory>
#include <memory_resource>
#include <mutex>
#include <net/if.h>
#include <optional>
#include <queue>
#include <shared_mutex>
#include <stdexcept>
#include <string>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/uio.h>
#include <sys/select.h>
#include <thread>
#include <unistd.h>
#include <unordered_map>
#include <variant>
#include <net/if.h> // for IFNAMSIZ
#include <linux/can.h>
#include <linux/can/raw.h>
#include "fmt/format.h"
namespace CAN
{
// Memory pool for efficient frame allocation
template<typename T, size_t POOL_SIZE = 1024>
class FramePool {
private:
alignas(T) std::array<uint8_t, sizeof(T) * POOL_SIZE> pool_storage;
std::array<bool, POOL_SIZE> used;
size_t next_free = 0;
public:
FramePool() {
used.fill(false);
}
[[nodiscard]] T* allocate() {
// Find next free slot
for (size_t i = 0; i < POOL_SIZE; ++i) {
size_t idx = (next_free + i) % POOL_SIZE;
if (!used[idx]) {
used[idx] = true;
next_free = (idx + 1) % POOL_SIZE;
return reinterpret_cast<T*>(pool_storage.data() + idx * sizeof(T));
}
}
return nullptr; // Pool exhausted
}
void deallocate(T* ptr) {
auto pool_start = reinterpret_cast<T*>(pool_storage.data());
auto pool_end = reinterpret_cast<T*>(pool_storage.data() + pool_storage.size());
if (ptr >= pool_start && ptr < pool_end) {
size_t idx = ptr - pool_start;
if (idx < POOL_SIZE) {
used[idx] = false;
}
}
}
[[nodiscard]] size_t available() const {
size_t count = 0;
for (bool is_used : used) {
if (!is_used) ++count;
}
return count;
}
[[nodiscard]] size_t capacity() const {
return POOL_SIZE;
}
};
// Batch operations for high-performance scenarios
struct BatchContext {
static constexpr size_t DEFAULT_BATCH_SIZE = 100;
size_t batch_size = DEFAULT_BATCH_SIZE;
std::chrono::microseconds timeout{1000};
bool use_zero_copy = true;
};
// Custom exception types for better error handling
class SocketException final : public std::runtime_error {
public:
explicit SocketException(const std::string& message) : std::runtime_error(message) {}
};
class FrameException final : public std::runtime_error {
public:
explicit FrameException(const std::string& message) : std::runtime_error(message) {}
};
class FilterException final : public std::runtime_error {
public:
explicit FilterException(const std::string& message) : std::runtime_error(message) {}
};
class IDException final : public std::runtime_error {
public:
explicit IDException(const std::string& message) : std::runtime_error(message) {}
};
// Socket protocol mode enum
enum class ProtocolMode {
ClassicCAN, // Classic CAN mode (CAN 2.0)
CanFD // CAN FD mode
};
// Classic CAN constants
constexpr uint32_t EFF_FLAG = CAN_EFF_FLAG; // EFF/SFF is set in the MSB
constexpr uint32_t RTR_FLAG = CAN_RTR_FLAG; // remote transmission request
constexpr uint32_t ERR_FLAG = CAN_ERR_FLAG; // error frame
constexpr uint32_t SFF_MASK = CAN_SFF_MASK; // standard frame
constexpr uint32_t EFF_MASK = CAN_EFF_MASK; // extended frame
constexpr uint32_t ERR_MASK = CAN_ERR_MASK; // omit EFF, RTR, ERR flags
// CAN FD Constants
namespace FD {
constexpr uint8_t MAX_DLC = 15; // Maximum DLC value for CAN FD
constexpr uint8_t MAX_DLEN = 64; // Maximum data length for CAN FD
constexpr uint8_t BRS_FLAG = CANFD_BRS; // Bit rate switch
constexpr uint8_t ESI_FLAG = CANFD_ESI; // Error state indicator
constexpr uint8_t FDF_FLAG = CANFD_FDF; // FD frame format
}
// CAN frame ID
// bit 0-28: CAN ID (11/29 bit)
// bit 29: error message frame flag (0=Data, 1=Error)
// bit 30: remote transmission request flag (RTR) (0=Data, 1=RTR)
// bit 31: frame format flag (0=Standard, 1=Extended)
class ID {
uint32_t id;
protected:
explicit ID(const uint32_t id) : id(id)
{
}
virtual ~ID() = default;
public:
[[nodiscard]] uint32_t get() const
{
return this->id;
}
};
// StandardID is a wrapper around ID
class StandardID final : public ID {
public:
// Constructor that validates and sets the value to fit in 11 bits
explicit StandardID(const uint32_t id) : ID(id & SFF_MASK)
{
// Throw exception if the original ID exceeded 11 bits
if ((id & ~SFF_MASK) != 0) {
throw IDException(fmt::format("ID value 0x{:x} exceeds 11-bit limit for Standard CAN ID (max: 0x{:x})", id, SFF_MASK));
}
}
// Template version for compile-time checking with literals
template <uint32_t id>
static StandardID create()
{
static_assert((id & ~SFF_MASK) == 0,
"Standard CAN ID exceeds 11-bit limit (0x7FF)");
return StandardID(id);
}
~StandardID() override = default;
[[nodiscard]] uint32_t justSFF() const
{
return get() & SFF_MASK;
}
};
// ExtendedID is a wrapper around ID
class ExtendedID final : public ID {
public:
// Constructor that validates and sets the value to fit in 29 bits
explicit ExtendedID(const uint32_t id) : ID((id & EFF_MASK) | EFF_FLAG)
{
// Throw exception if the original ID exceeded 29 bits
if ((id & ~EFF_MASK) != 0) {
throw IDException(fmt::format("ID value 0x{:x} exceeds 29-bit limit for Extended CAN ID (max: 0x{:x})", id, EFF_MASK));
}
}
// Template version for compile-time checking with literals
template <uint32_t id>
static ExtendedID create()
{
static_assert((id & ~EFF_MASK) == 0,
"Extended CAN ID exceeds 29-bit limit (0x1FFFFFFF)");
return ExtendedID(id);
}
~ExtendedID() override = default;
[[nodiscard]] uint32_t justEFF() const
{
return get() & EFF_MASK;
}
};
// CAN frame is always 16 bytes on linux,
// regardless of the actual data payload size.
// Bytes 0-3 : CAN ID
// Byte 4 : Frame payload length in bytes
// Bytes 5-7 : Reserved
// Bytes 8-15 : Frame payload
class Frame final {
public:
uint32_t id;
uint8_t dlc;
std::array<uint8_t, 8> data;
std::optional<timespec> hw_timestamp;
// Default constructor (needed for containers)
Frame() : id(0), dlc(0), data{}, hw_timestamp(std::nullopt) {}
Frame(const uint32_t id, const uint8_t dlc, const std::array<uint8_t, 8>& data)
: id(id), dlc(dlc), data(data), hw_timestamp(std::nullopt)
{
validateFrame();
}
Frame(const StandardID& id, const uint8_t dlc, const std::array<uint8_t, 8>& data)
: id(id.get()), dlc(dlc), data(data), hw_timestamp(std::nullopt)
{
validateFrame();
}
Frame(const ExtendedID& id, const uint8_t dlc, const std::array<uint8_t, 8>& data)
: id(id.get()), dlc(dlc), data(data), hw_timestamp(std::nullopt)
{
validateFrame();
}
Frame(const uint32_t id, const uint8_t dlc, const std::array<uint8_t, 8>& data, const timespec& timestamp)
: id(id), dlc(dlc), data(data), hw_timestamp(timestamp)
{
validateFrame();
}
// Copy constructor
Frame(const Frame& other) = default;
// Move constructor
Frame(Frame&& other) noexcept = default;
// Copy assignment
Frame& operator=(const Frame& other) = default;
// Move assignment
Frame& operator=(Frame&& other) noexcept = default;
~Frame() = default;
private:
void validateFrame() const {
if (dlc > 8) {
throw FrameException("DLC cannot exceed 8 bytes for standard CAN frames");
}
}
public:
[[nodiscard]] uint32_t getCANID() const noexcept
{
// check if EFF flag is set
if (id & EFF_FLAG) {
return id & EFF_MASK;
}
// otherwise, it's a standard frame
return id & SFF_MASK;
}
[[nodiscard]] bool isExtended() const noexcept {
return (id & EFF_FLAG) != 0;
}
[[nodiscard]] bool isRTR() const noexcept {
return (id & RTR_FLAG) != 0;
}
[[nodiscard]] bool isError() const noexcept {
return (id & ERR_FLAG) != 0;
}
// Stream output operator for debugging
friend std::ostream& operator<<(std::ostream& os, const Frame& frame) {
os << "CAN Frame [ID: 0x" << std::hex << std::uppercase;
if (frame.isExtended()) {
os << std::setfill('0') << std::setw(8);
}
os << frame.getCANID() << std::nouppercase << std::dec
<< ", DLC: " << static_cast<int>(frame.dlc)
<< ", Data: [";
for (size_t i = 0; i < frame.dlc && i < 8; ++i) {
if (i > 0) os << ", ";
os << "0x" << std::hex << std::setfill('0') << std::setw(2)
<< static_cast<int>(frame.data[i]) << std::dec;
}
os << "]";
if (frame.isExtended()) os << " (Extended)";
if (frame.isRTR()) os << " (RTR)";
if (frame.isError()) os << " (Error)";
return os;
}
};
// Frame Builder Pattern for convenient frame construction
class FrameBuilder {
private:
uint32_t id = 0;
uint8_t dlc = 0;
std::array<uint8_t, 8> data{};
std::optional<timespec> timestamp;
public:
FrameBuilder& setID(uint32_t id) {
this->id = id;
return *this;
}
FrameBuilder& setID(const StandardID& id) {
this->id = id.get();
return *this;
}
FrameBuilder& setID(const ExtendedID& id) {
this->id = id.get();
return *this;
}
FrameBuilder& setDLC(uint8_t dlc) {
this->dlc = dlc;
return *this;
}
FrameBuilder& setData(const std::array<uint8_t, 8>& data) {
this->data = data;
if (dlc == 0) {
dlc = 8; // When setting a full array, assume DLC of 8
}
return *this;
}
FrameBuilder& setData(const std::vector<uint8_t>& data) {
std::fill(this->data.begin(), this->data.end(), 0);
size_t copy_len = std::min(data.size(), size_t(8));
std::copy(data.begin(), data.begin() + copy_len, this->data.begin());
if (dlc == 0) {
dlc = static_cast<uint8_t>(copy_len);
}
return *this;
}
FrameBuilder& setData(const std::initializer_list<uint8_t>& data) {
std::fill(this->data.begin(), this->data.end(), 0);
size_t copy_len = std::min(data.size(), size_t(8));
std::copy(data.begin(), data.begin() + copy_len, this->data.begin());
if (dlc == 0) {
dlc = static_cast<uint8_t>(copy_len);
}
return *this;
}
FrameBuilder& setTimestamp(const timespec& timestamp) {
this->timestamp = timestamp;
return *this;
}
[[nodiscard]] Frame build() const {
if (timestamp) {
return Frame(id, dlc, data, *timestamp);
} else {
return Frame(id, dlc, data);
}
}
// Convenience method for creating a frame with automatic DLC
[[nodiscard]] Frame buildAuto() const {
uint8_t actual_dlc = dlc;
if (actual_dlc == 0) {
// Calculate DLC based on non-zero data
actual_dlc = 8;
for (int i = 7; i >= 0; --i) {
if (data[i] != 0) {
actual_dlc = i + 1;
break;
}
}
}
if (timestamp) {
return Frame(id, actual_dlc, data, *timestamp);
} else {
return Frame(id, actual_dlc, data);
}
}
};
// Forward declaration of the Socket class
class Socket;
namespace FD {
// CAN FD frame with up to 64 bytes of data
class Frame final {
public:
uint32_t id;
uint8_t len; // Frame payload length in bytes (0-64)
uint8_t flags; // Additional flags for CAN FD (BRS, ESI, FDF)
std::array<uint8_t, FD::MAX_DLEN> data;
std::optional<timespec> hw_timestamp;
// Static helper method to convert a standard CAN frame to CAN FD frame
static Frame fromCANFrame(const CAN::Frame& canFrame, const bool withBitRateSwitch = false) {
// Create a new CAN FD frame with the same ID and data
std::array<uint8_t, FD::MAX_DLEN> fdData{};
// Copy data from CAN frame (maximum 8 bytes)
for (int i = 0; i < canFrame.dlc && i < 8; i++) {
fdData[i] = canFrame.data[i];
}
// Create FD frame with appropriate flags
const uint8_t fdFlags = withBitRateSwitch ?
FD::FDF_FLAG | FD::BRS_FLAG :
FD::FDF_FLAG;
// Preserve any hardware timestamp
if (canFrame.hw_timestamp) {
return Frame(canFrame.id, canFrame.dlc, fdData, *canFrame.hw_timestamp, fdFlags);
} else {
return Frame(canFrame.id, canFrame.dlc, fdData, fdFlags);
}
}
// Constructor with array data
Frame(const uint32_t id, const uint8_t len, const std::array<uint8_t, FD::MAX_DLEN>& data, const uint8_t flags = FD::FDF_FLAG)
: id(id), len(len), flags(flags), data(data), hw_timestamp(std::nullopt)
{
// Always set the FDF flag to indicate a CAN FD frame
this->flags |= FD::FDF_FLAG;
validateFrame();
}
// Constructors with ID objects
Frame(const StandardID& id, const uint8_t len, const std::array<uint8_t, FD::MAX_DLEN>& data, const uint8_t flags = FD::FDF_FLAG)
: id(id.get()), len(len), flags(flags), data(data), hw_timestamp(std::nullopt)
{
this->flags |= FD::FDF_FLAG;
validateFrame();
}
Frame(const ExtendedID& id, const uint8_t len, const std::array<uint8_t, FD::MAX_DLEN>& data, const uint8_t flags = FD::FDF_FLAG)
: id(id.get()), len(len), flags(flags), data(data), hw_timestamp(std::nullopt)
{
this->flags |= FD::FDF_FLAG;
validateFrame();
}
// Constructor with timestamp
Frame(const uint32_t id, const uint8_t len, const std::array<uint8_t, FD::MAX_DLEN>& data,
const timespec& timestamp, const uint8_t flags = FD::FDF_FLAG)
: id(id), len(len), flags(flags), data(data), hw_timestamp(timestamp)
{
this->flags |= FD::FDF_FLAG;
validateFrame();
}
// Copy constructor
Frame(const Frame& other) = default;
// Move constructor
Frame(Frame&& other) noexcept = default;
// Copy assignment
Frame& operator=(const Frame& other) = default;
// Move assignment
Frame& operator=(Frame&& other) noexcept = default;
~Frame() = default;
private:
void validateFrame() const {
if (len > FD::MAX_DLEN) {
throw FrameException("Frame length cannot exceed 64 bytes for CAN FD frames");
}
}
public:
// Vector data constructor for flexible length input
Frame(const uint32_t id, const std::vector<uint8_t>& vec_data, const uint8_t flags = FD::FDF_FLAG)
: id(id), len(static_cast<uint8_t>(vec_data.size())), flags(flags), hw_timestamp(std::nullopt)
{
this->flags |= FD::FDF_FLAG;
// Copy data from vector to array
std::fill(data.begin(), data.end(), 0); // Initialize with zeros
std::copy(vec_data.begin(), vec_data.end(), data.begin());
validateFrame();
}
[[nodiscard]] uint32_t getCANID() const noexcept
{
// Check if EFF flag is set
if (id & EFF_FLAG) {
return id & EFF_MASK;
}
// Otherwise, it's a standard frame
return id & SFF_MASK;
}
[[nodiscard]] bool isExtended() const noexcept {
return (id & EFF_FLAG) != 0;
}
[[nodiscard]] bool isRTR() const noexcept {
return (id & RTR_FLAG) != 0;
}
[[nodiscard]] bool isError() const noexcept {
return (id & ERR_FLAG) != 0;
}
// Set/get flags related methods
void setBRS(bool enable)
{
if (enable) {
flags |= FD::BRS_FLAG;
} else {
flags &= ~FD::BRS_FLAG;
}
}
[[nodiscard]] bool hasBRS() const noexcept
{
return (flags & FD::BRS_FLAG) != 0;
}
void setESI(bool enable)
{
if (enable) {
flags |= FD::ESI_FLAG;
} else {
flags &= ~FD::ESI_FLAG;
}
}
[[nodiscard]] bool hasESI() const noexcept
{
return (flags & FD::ESI_FLAG) != 0;
}
// Stream output operator for debugging
friend std::ostream& operator<<(std::ostream& os, const Frame& frame) {
os << "CAN FD Frame [ID: 0x" << std::hex << frame.getCANID() << std::dec
<< ", Length: " << static_cast<int>(frame.len)
<< ", Data: [";
for (size_t i = 0; i < frame.len && i < FD::MAX_DLEN; ++i) {
if (i > 0) os << ", ";
os << "0x" << std::hex << std::setfill('0') << std::setw(2)
<< static_cast<int>(frame.data[i]) << std::dec;
}
os << "], Flags: [";
if (frame.hasBRS()) os << "BRS ";
if (frame.hasESI()) os << "ESI ";
os << "FDF]";
if (frame.isExtended()) os << " (Extended)";
if (frame.isRTR()) os << " (RTR)";
if (frame.isError()) os << " (Error)";
return os;
}
};
// CAN FD Frame Builder Pattern
class FrameBuilder {
private:
uint32_t id = 0;
uint8_t len = 0;
uint8_t flags = FD::FDF_FLAG;
std::array<uint8_t, FD::MAX_DLEN> data{};
std::optional<timespec> timestamp;
public:
FrameBuilder& setID(uint32_t id) {
this->id = id;
return *this;
}
FrameBuilder& setID(const StandardID& id) {
this->id = id.get();
return *this;
}
FrameBuilder& setID(const ExtendedID& id) {
this->id = id.get();
return *this;
}
FrameBuilder& setLength(uint8_t len) {
this->len = len;
return *this;
}
FrameBuilder& setData(const std::array<uint8_t, FD::MAX_DLEN>& data) {
this->data = data;
return *this;
}
FrameBuilder& setData(const std::vector<uint8_t>& data) {
std::fill(this->data.begin(), this->data.end(), 0);
size_t copy_len = std::min(data.size(), size_t(FD::MAX_DLEN));
std::copy(data.begin(), data.begin() + copy_len, this->data.begin());
if (len == 0) {
len = static_cast<uint8_t>(copy_len);
}
return *this;
}
FrameBuilder& setData(const std::initializer_list<uint8_t>& data) {
std::fill(this->data.begin(), this->data.end(), 0);
size_t copy_len = std::min(data.size(), size_t(FD::MAX_DLEN));
std::copy(data.begin(), data.begin() + copy_len, this->data.begin());
if (len == 0) {
len = static_cast<uint8_t>(copy_len);
}
return *this;
}
FrameBuilder& enableBRS(bool enable = true) {
if (enable) {
flags |= FD::BRS_FLAG;
} else {
flags &= ~FD::BRS_FLAG;
}
return *this;
}
FrameBuilder& enableESI(bool enable = true) {
if (enable) {
flags |= FD::ESI_FLAG;
} else {
flags &= ~FD::ESI_FLAG;
}
return *this;
}
FrameBuilder& setTimestamp(const timespec& timestamp) {
this->timestamp = timestamp;
return *this;
}
[[nodiscard]] Frame build() const {
if (timestamp) {
return Frame(id, len, data, *timestamp, flags);
} else {
return Frame(id, len, data, flags);
}
}
// Convenience method for creating a frame with automatic length
[[nodiscard]] Frame buildAuto() const {
uint8_t actual_len = len;
if (actual_len == 0) {
// Calculate length based on non-zero data
actual_len = FD::MAX_DLEN;
for (int i = FD::MAX_DLEN - 1; i >= 0; --i) {
if (data[i] != 0) {
actual_len = i + 1;
break;
}
}
}
if (timestamp) {
return Frame(id, actual_len, data, *timestamp, flags);
} else {
return Frame(id, actual_len, data, flags);
}
}
};
} // namespace FD
// Unified Socket class that can handle both CAN and CAN FD frames
class Socket {
int sock;
ProtocolMode mode;
private:
// Helper function to wait for socket readability with timeout
[[nodiscard]] bool waitForRead(std::optional<std::chrono::milliseconds> timeout) const {
if (!timeout.has_value()) {
return true; // No timeout specified, rely on socket timeout
}
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(sock, &readfds);
timeval tv;
tv.tv_sec = timeout->count() / 1000;
tv.tv_usec = (timeout->count() % 1000) * 1000;
int result = select(sock + 1, &readfds, nullptr, nullptr, &tv);
if (result == -1) {
throw SocketException(fmt::format("Select failed during read timeout: {}", strerror(errno)));
}
return result > 0; // Returns true if data is available
}
// Helper function to wait for socket writability with timeout
[[nodiscard]] bool waitForWrite(std::optional<std::chrono::milliseconds> timeout) const {
if (!timeout.has_value()) {
return true; // No timeout specified
}
fd_set writefds;
FD_ZERO(&writefds);
FD_SET(sock, &writefds);
timeval tv;
tv.tv_sec = timeout->count() / 1000;
tv.tv_usec = (timeout->count() % 1000) * 1000;
int result = select(sock + 1, nullptr, &writefds, nullptr, &tv);
if (result == -1) {
throw SocketException(fmt::format("Select failed during write timeout: {}", strerror(errno)));
}
return result > 0; // Returns true if socket is writable
}
// Helper to temporarily set socket to non-blocking mode
class NonBlockingGuard {
int sock;
int original_flags;
bool was_changed;
public:
explicit NonBlockingGuard(int socket_fd) : sock(socket_fd), was_changed(false) {
original_flags = fcntl(sock, F_GETFL, 0);
if (original_flags == -1) {
throw SocketException(fmt::format("Failed to get socket flags: {}", strerror(errno)));
}
if (!(original_flags & O_NONBLOCK)) {
if (fcntl(sock, F_SETFL, original_flags | O_NONBLOCK) == -1) {
throw SocketException(fmt::format("Failed to set non-blocking mode: {}", strerror(errno)));
}
was_changed = true;
}
}
~NonBlockingGuard() {
if (was_changed) {
fcntl(sock, F_SETFL, original_flags); // Restore original flags
}
}
// Delete copy constructor and assignment
NonBlockingGuard(const NonBlockingGuard&) = delete;
NonBlockingGuard& operator=(const NonBlockingGuard&) = delete;
};
public:
explicit Socket(const std::string& interface,
const ProtocolMode mode = ProtocolMode::ClassicCAN,
const std::chrono::milliseconds& timeout = std::chrono::milliseconds(100),
const int rcvbuf_size = 327680)
: mode(mode)
{
this->sock = socket(PF_CAN, SOCK_RAW, CAN_RAW);
if (this->sock == -1) {
throw SocketException(fmt::format("Failed to create CAN socket: {}", strerror(errno)));
}
// Enable CAN FD frames if requested
if (mode == ProtocolMode::CanFD) {
try {
setSocketOption(SOL_CAN_RAW, CAN_RAW_FD_FRAMES, 1, "Failed to enable CAN FD frames");
} catch (const std::exception& e) {
::close(this->sock);
throw SocketException(fmt::format("Failed to enable CAN FD frames: {}", e.what()));
}
}
// Get interface
ifreq ifr{};
strncpy(ifr.ifr_name, interface.c_str(), IFNAMSIZ - 1);
// Ensure null termination
ifr.ifr_name[IFNAMSIZ - 1] = '\0';
if (ioctl(this->sock, SIOCGIFINDEX, &ifr) == -1) {
::close(this->sock);
throw SocketException(fmt::format("Failed to get CAN interface '{}': {}", interface, strerror(errno)));
}
// Set timeout
timeval tv{};
tv.tv_sec = timeout.count() / 1000;
tv.tv_usec = (timeout.count() % 1000) * 1000;
if (setsockopt(this->sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) == -1) {
::close(this->sock);
throw SocketException(fmt::format("Failed to set CAN socket timeout: {}", strerror(errno)));
}
// Set address
sockaddr_can addr{};
memset(&addr, 0, sizeof(addr));
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
// Bind
if (bind(this->sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) == -1) {
::close(this->sock);
throw SocketException(fmt::format("Failed to bind CAN socket to interface '{}': {}", interface, strerror(errno)));
}
// Set receive buffer size if specified
if (rcvbuf_size > 0) {
try {
setSocketOption(SOL_SOCKET, SO_RCVBUF, rcvbuf_size, "Failed to set socket receive buffer size");
} catch (const std::exception& e) {
::close(this->sock);
throw SocketException(fmt::format("Failed to set socket receive buffer size: {}", e.what()));
}
}
}
// Disable copy construction and assignment
Socket(const Socket&) = delete;
Socket& operator=(const Socket&) = delete;
// Enable move construction and assignment
Socket(Socket&& other) noexcept : sock(other.sock), mode(other.mode) {
other.sock = -1;
}
Socket& operator=(Socket&& other) noexcept {
if (this != &other) {
close();
sock = other.sock;
mode = other.mode;
other.sock = -1;
}
return *this;
}
~Socket()
{
close();
}
// Get the current mode (CAN or CAN FD)
[[nodiscard]] ProtocolMode getMode() const
{
return mode;
}
// Generic helper for setting socket options
template<typename T>
void setSocketOption(int level, int option_name, const T& value, const std::string& error_message) const {
if (!isOpen()) {
throw SocketException("Socket is not open");
}
if (setsockopt(this->sock, level, option_name, &value, sizeof(value)) == -1) {
throw SocketException(fmt::format("{}: {}", error_message, strerror(errno)));
}
}
// Generic helper for getting socket options
template<typename T>
T getSocketOption(int level, int option_name, const std::string& error_message) const {
if (!isOpen()) {
throw SocketException("Socket is not open");
}
T value;
socklen_t len = sizeof(value);
if (getsockopt(this->sock, level, option_name, &value, &len) == -1) {
throw SocketException(fmt::format("{}: {}", error_message, strerror(errno)));
}
return value;
}
// Set the socket receive buffer size
int setReceiveBufferSize(const int size) const
{
if (size <= 0) {
throw std::invalid_argument("Buffer size must be positive");
}
setSocketOption(SOL_SOCKET, SO_RCVBUF, size, "Failed to set socket receive buffer size");
// Verify the buffer size was set
int actual_size = getReceiveBufferSize();
// Linux doubles the value we set, so divide by 2 for comparison
if (actual_size / 2 < size) {
throw std::runtime_error(fmt::format(
"Failed to set receive buffer size to {}, actual size is {}", size, actual_size / 2));
}
return actual_size / 2; // Return the actual size (accounting for Linux doubling)
}
// Get the current socket receive buffer size
[[nodiscard]] int getReceiveBufferSize() const
{
return getSocketOption<int>(SOL_SOCKET, SO_RCVBUF, "Failed to get socket receive buffer size");
// Note: This is doubled by Linux
}
[[nodiscard]] int getFd() const noexcept
{
return this->sock;
}
void close() noexcept
{
if (isOpen() == false) {
return;
}
::close(this->sock);
this->sock = -1;
}
[[nodiscard]] bool isOpen() const noexcept
{
return this->sock != -1;
}
[[nodiscard]] int setFilter(const uint32_t id, const uint32_t mask) const
{
can_filter filter[1];
filter[0].can_id = id;
filter[0].can_mask = mask;
// Using plain setsockopt because the templated version expects a reference to a single value
if (!isOpen()) {
throw SocketException("Socket is not open");
}
if (setsockopt(this->sock, SOL_CAN_RAW, CAN_RAW_FILTER, &filter, sizeof(filter)) == -1) {
throw FilterException(fmt::format("Failed to set CAN filter (ID: 0x{:x}, Mask: 0x{:x}): {}", id, mask, strerror(errno)));
}
return 0;
}
[[nodiscard]] int setFilter(const StandardID& id, const uint32_t mask) const
{
return setFilter(id.get(), mask);
}
[[nodiscard]] int setFilter(const ExtendedID& id, const uint32_t mask) const
{
return setFilter(id.get(), mask);
}
// Base implementation for setting CAN filters
[[nodiscard]] int setFilters(const std::vector<std::pair<uint32_t, uint32_t>>& filters) const
{