-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathcanard_sitl_driver.c
More file actions
393 lines (328 loc) · 10.4 KB
/
Copy pathcanard_sitl_driver.c
File metadata and controls
393 lines (328 loc) · 10.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
/*
* canard_sitl_driver.c
*
* SITL CAN Driver - SocketCAN implementation for Linux
* Falls back to stub mode on non-Linux platforms or if socket fails
*
* Created: 2026-02-12
*/
#include "platform.h"
#if defined(SITL_BUILD) && defined(USE_DRONECAN)
#include "canard.h"
#include "canard_stm32_driver.h"
#include "common/log.h"
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#ifdef __linux__
#include <sys/socket.h>
#include <sys/select.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <linux/can.h>
#include <linux/can/raw.h>
#endif
// Driver state
typedef enum {
SITL_CAN_MODE_STUB = 0,
SITL_CAN_MODE_SOCKETCAN
} sitlCANMode_e;
static bool driver_initialized = false;
static sitlCANMode_e can_mode = SITL_CAN_MODE_STUB;
#ifdef __linux__
static int can_socket = -1;
static char can_interface_name[IFNAMSIZ] = DRONECAN_SITL_INTERFACE;
#endif
// Forward declarations
static int16_t sitlCANInitStub(uint32_t bitrate);
static int16_t sitlCANReceiveStub(CanardCANFrame *const rx_frame);
static int16_t sitlCANTransmitStub(const CanardCANFrame* const tx_frame);
static void sitlCANGetStatsStub(canardProtocolStatus_t *pProtocolStat);
#ifdef __linux__
static int16_t sitlCANInitSocketCAN(uint32_t bitrate);
static int16_t sitlCANReceiveSocketCAN(CanardCANFrame *const rx_frame);
static int16_t sitlCANTransmitSocketCAN(const CanardCANFrame* const tx_frame);
static void sitlCANGetStatsSocketCAN(canardProtocolStatus_t *pProtocolStat);
#endif
/**
* @brief Initialize CAN interface with SocketCAN (Linux) or stub fallback
* @param bitrate CAN bitrate in bps
* @retval 0 on success, negative on error
*/
int16_t canardSTM32CAN1_Init(uint32_t bitrate) {
if (driver_initialized) {
return 0; // Already initialized
}
#ifdef __linux__
// Try SocketCAN first
if (sitlCANInitSocketCAN(bitrate) == 0) {
can_mode = SITL_CAN_MODE_SOCKETCAN;
driver_initialized = true;
LOG_INFO(CAN, "DroneCAN SITL driver initialized (SocketCAN on %s)", can_interface_name);
return 0;
}
// Fall back to stub mode
LOG_WARNING(CAN, "SocketCAN initialization failed, falling back to stub mode");
#endif
// Use stub mode (non-Linux or SocketCAN failed)
can_mode = SITL_CAN_MODE_STUB;
driver_initialized = true;
sitlCANInitStub(bitrate);
return 0;
}
// Stub implementations
static int16_t sitlCANInitStub(uint32_t bitrate) {
(void)bitrate;
LOG_DEBUG(CAN, "SITL DroneCAN driver initialized (stub mode)");
return 0;
}
static int16_t sitlCANReceiveStub(CanardCANFrame *const rx_frame) {
(void)rx_frame;
return 0; // No data available in stub mode
}
static int16_t sitlCANTransmitStub(const CanardCANFrame* const tx_frame) {
(void)tx_frame;
return 1; // Success (frame "transmitted")
}
static void sitlCANGetStatsStub(canardProtocolStatus_t *pProtocolStat) {
memset(pProtocolStat, 0, sizeof(*pProtocolStat));
}
#ifdef __linux__
// SocketCAN implementations
static int16_t sitlCANInitSocketCAN(uint32_t bitrate) {
struct sockaddr_can addr;
struct ifreq ifr;
// Create CAN socket
can_socket = socket(PF_CAN, SOCK_RAW, CAN_RAW);
if (can_socket < 0) {
LOG_ERROR(CAN, "Failed to create CAN socket: %s", strerror(errno));
return -1;
}
// Set non-blocking mode
int flags = fcntl(can_socket, F_GETFL, 0);
if (fcntl(can_socket, F_SETFL, flags | O_NONBLOCK) < 0) {
LOG_ERROR(CAN, "Failed to set non-blocking mode: %s", strerror(errno));
close(can_socket);
can_socket = -1;
return -1;
}
// Get interface index
strncpy(ifr.ifr_name, can_interface_name, IFNAMSIZ - 1);
ifr.ifr_name[IFNAMSIZ - 1] = '\0';
if (ioctl(can_socket, SIOCGIFINDEX, &ifr) < 0) {
LOG_ERROR(CAN, "Failed to get interface index for %s: %s", can_interface_name, strerror(errno));
close(can_socket);
can_socket = -1;
return -1;
}
// Bind to CAN interface
memset(&addr, 0, sizeof(addr));
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
if (bind(can_socket, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
LOG_ERROR(CAN, "Failed to bind to CAN interface %s: %s", can_interface_name, strerror(errno));
close(can_socket);
can_socket = -1;
return -1;
}
LOG_INFO(CAN, "SocketCAN initialized on %s at %lu bps", can_interface_name, (unsigned long)bitrate);
return 0;
}
static void sitlCANFrameToLinux(const CanardCANFrame *const src, struct can_frame *const dst) {
memset(dst, 0, sizeof(struct can_frame));
// Handle extended frame format (EFF) - DroneCAN uses 29-bit IDs
if (src->id & CANARD_CAN_FRAME_EFF) {
dst->can_id = (src->id & CANARD_CAN_EXT_ID_MASK) | CAN_EFF_FLAG;
} else {
dst->can_id = src->id & CANARD_CAN_STD_ID_MASK;
}
if (src->id & CANARD_CAN_FRAME_RTR) {
dst->can_id |= CAN_RTR_FLAG;
}
// Copy data
dst->can_dlc = src->data_len;
if (src->data_len > 0) {
memcpy(dst->data, src->data, src->data_len);
}
}
static void sitlCANFrameFromLinux(const struct can_frame *const src, CanardCANFrame *const dst) {
memset(dst, 0, sizeof(CanardCANFrame));
// Handle extended frame format
if (src->can_id & CAN_EFF_FLAG) {
dst->id = (src->can_id & CANARD_CAN_EXT_ID_MASK) | CANARD_CAN_FRAME_EFF;
} else {
dst->id = src->can_id & CANARD_CAN_STD_ID_MASK;
}
if (src->can_id & CAN_RTR_FLAG) {
dst->id |= CANARD_CAN_FRAME_RTR;
}
// Copy data
dst->data_len = src->can_dlc;
if (src->can_dlc > 0) {
memcpy(dst->data, src->data, src->can_dlc);
}
}
static int16_t sitlCANReceiveSocketCAN(CanardCANFrame *const rx_frame) {
struct can_frame frame;
ssize_t nbytes;
if (can_socket < 0) {
return -1;
}
// Non-blocking receive
nbytes = read(can_socket, &frame, sizeof(struct can_frame));
if (nbytes < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return 0; // No data available
}
LOG_ERROR(CAN, "SocketCAN receive error: %s", strerror(errno));
return -1;
}
if (nbytes != sizeof(struct can_frame)) {
LOG_WARNING(CAN, "Incomplete CAN frame received");
return 0;
}
sitlCANFrameFromLinux(&frame, rx_frame);
return 1;
}
static int16_t sitlCANTransmitSocketCAN(const CanardCANFrame* const tx_frame) {
struct can_frame frame;
ssize_t nbytes;
if (can_socket < 0) {
return -1;
}
sitlCANFrameToLinux(tx_frame, &frame);
nbytes = write(can_socket, &frame, sizeof(struct can_frame));
if (nbytes < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return 0; // Busy, try again later
}
LOG_ERROR(CAN, "SocketCAN transmit error: %s", strerror(errno));
return -1;
}
return 1; // Success
}
/* Always returns zeroes — SocketCAN provides no per-frame error counters via raw sockets. */
static void sitlCANGetStatsSocketCAN(canardProtocolStatus_t *pProtocolStat) {
memset(pProtocolStat, 0, sizeof(*pProtocolStat));
}
#endif // __linux__
/**
* @brief Receive a CAN frame via SocketCAN or stub
* @param rx_frame Pointer to frame structure to fill
* @retval 0 if no frame available, 1 if frame received, negative on error
*/
int16_t canardSTM32Receive(CanardCANFrame *const rx_frame) {
if (rx_frame == NULL) {
return -CANARD_ERROR_INVALID_ARGUMENT;
}
if (!driver_initialized) {
return -CANARD_ERROR_INTERNAL;
}
#ifdef __linux__
if (can_mode == SITL_CAN_MODE_SOCKETCAN) {
return sitlCANReceiveSocketCAN(rx_frame);
}
#endif
return sitlCANReceiveStub(rx_frame);
}
/**
* @brief Transmit a CAN frame via SocketCAN or stub
* @param tx_frame Pointer to frame to transmit
* @retval 1 on success, 0 if busy, negative on error
*/
int16_t canardSTM32Transmit(const CanardCANFrame* const tx_frame) {
if (tx_frame == NULL || (tx_frame->id & CANARD_CAN_FRAME_ERR)) {
return -CANARD_ERROR_INVALID_ARGUMENT;
}
if (!driver_initialized) {
return -CANARD_ERROR_INTERNAL;
}
#ifdef __linux__
if (can_mode == SITL_CAN_MODE_SOCKETCAN) {
return sitlCANTransmitSocketCAN(tx_frame);
}
#endif
return sitlCANTransmitStub(tx_frame);
}
/**
* @brief Get CAN protocol status
* @param pProtocolStat Pointer to status structure to fill
*/
void canardSTM32GetProtocolStatus(canardProtocolStatus_t *pProtocolStat) {
if (pProtocolStat == NULL) {
return;
}
#ifdef __linux__
if (can_mode == SITL_CAN_MODE_SOCKETCAN) {
sitlCANGetStatsSocketCAN(pProtocolStat);
return;
}
#endif
sitlCANGetStatsStub(pProtocolStat);
}
/**
* @brief Get RX FIFO fill level
* @retval Number of frames in RX FIFO
*/
int32_t canardSTM32GetRxFifoFillLevel(void) {
#ifdef __linux__
if (can_mode == SITL_CAN_MODE_SOCKETCAN && can_socket >= 0) {
int available;
/* FIONREAD on SOCK_RAW returns the byte size of the next pending datagram only,
so this yields 0 or 1 — SITL processes at most one frame per scheduler tick. */
if (ioctl(can_socket, FIONREAD, &available) == 0) {
return available / (int)sizeof(struct can_frame);
}
}
#endif
return 0;
}
uint32_t canardSTM32GetAndClearRxDropCount(void) {
return 0;
}
int32_t canardSTM32GetTxQueueFillLevel(void) {
return 0;
}
/**
* @brief Recover from bus-off condition
*/
void canardSTM32RecoverFromBusOff(void) {
// For SocketCAN, interface recovery is handled by the kernel
// For stub, nothing to do
}
/**
* @brief Get unique ID for this node
* @param id 16-byte buffer to fill with unique ID
*/
void canardSTM32GetUniqueID(uint8_t id[16]) {
if (id == NULL) {
return;
}
memset(id, 0, 16);
// "SITL" marker in first 4 bytes
id[0] = 'S';
id[1] = 'I';
id[2] = 'T';
id[3] = 'L';
#ifdef __linux__
// Add process ID for uniqueness between multiple SITL instances
uint32_t upid = (uint32_t)getpid();
id[4] = (upid >> 24) & 0xFF;
id[5] = (upid >> 16) & 0xFF;
id[6] = (upid >> 8) & 0xFF;
id[7] = upid & 0xFF;
// Add timestamp for additional uniqueness
struct timespec ts;
if (clock_gettime(CLOCK_REALTIME, &ts) == 0) {
id[8] = (ts.tv_sec >> 24) & 0xFF;
id[9] = (ts.tv_sec >> 16) & 0xFF;
id[10] = (ts.tv_sec >> 8) & 0xFF;
id[11] = ts.tv_sec & 0xFF;
}
#endif
}
#endif // SITL_BUILD && USE_DRONECAN