2 * Copyright (C) 2015, 2016 "IoT.bzh"
3 * Author "Romain Forlot" <romain.forlot@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
29 #include <sys/ioctl.h>
30 #include <linux/can.h>
31 #include <sys/socket.h>
32 #include <linux/can/raw.h>
35 #include "openxc.pb.h"
39 #include <afb/afb-binding.h>
40 #include <afb/afb-service-itf.h>
43 // TODO actual max is 32 but dropped to 24 for memory considerations
44 #define MAX_ACCEPTANCE_FILTERS 24
45 // TODO this takes up a ton of memory
46 #define MAX_DYNAMIC_MESSAGE_COUNT 12
48 #define CAN_MESSAGE_SIZE 8
50 #define CAN_ACTIVE_TIMEOUT_S 30
53 * @brief Function representing thread activated by can bus objects
55 void can_reader(can_bus_dev_t& can_bus);
56 void can_decode_message(can_bus_t& can_bus);
57 void can_event_push(can_bus_t& can_bus);
60 * @brief The type signature for a CAN signal decoder.
62 * @desc A SignalDecoder transforms a raw floating point CAN signal into a number,
65 * @param[in] CanSignal signal - The CAN signal that we are decoding.
66 * @param[in] CanSignal signals - The list of all signals.
67 * @param[in] int signalCount - The length of the signals array.
68 * @param[in] float value - The CAN signal parsed from the message as a raw floating point
70 * @param[out] bool send - An output parameter. If the decoding failed or the CAN signal should
71 * not send for some other reason, this should be flipped to false.
73 * @return a decoded value in an openxc_DynamicField struct.
75 typedef openxc_DynamicField (*SignalDecoder)(struct CanSignal* signal,
76 CanSignal* signals, int signalCount, float value, bool* send);
79 * @brief: The type signature for a CAN signal encoder.
81 * @desc A SignalEncoder transforms a number, string or boolean into a raw floating
82 * point value that fits in the CAN signal.
84 * @params[signal] - The CAN signal to encode.
85 * @params[value] - The dynamic field to encode.
86 * @params[send] - An output parameter. If the encoding failed or the CAN signal should
87 * not be encoded for some other reason, this will be flipped to false.
89 typedef uint64_t (*SignalEncoder)(struct CanSignal* signal,
90 openxc_DynamicField* value, bool* send);
93 * @brief The ID format for a CAN message.
95 * STANDARD - standard 11-bit CAN arbitration ID.
96 * EXTENDED - an extended frame, with a 29-bit arbitration ID.
98 enum CanMessageFormat {
102 typedef enum CanMessageFormat CanMessageFormat;
105 * @brief A compact representation of a single CAN message, meant to be used in in/out
108 * param[in] uint32_t id - The ID of the message.
109 * param[in] CanMessageFormat format - the format of the message's ID.
110 * param[in] uint8_t data - The message's data field.
111 * @param[in] uint8_t length - the length of the data array (max 8).
112 *************************
113 * old CanMessage struct *
114 *************************
117 CanMessageFormat format;
118 uint8_t data[CAN_MESSAGE_SIZE];
121 typedef struct CanMessage CanMessage;
123 class can_message_t {
125 const struct afb_binding_interface *interface_;
127 CanMessageFormat format_;
128 uint8_t data_[CAN_MESSAGE_SIZE];
132 uint32_t get_id() const;
133 int get_format() const;
134 uint8_t get_data() const;
135 uint8_t get_lenght() const;
137 void set_id(uint32_t id);
138 void set_format(CanMessageFormat format);
139 void set_data(uint8_t data);
140 void set_lenght(uint8_t length);
142 void convert_from_canfd_frame(canfd_frame frame);
143 canfd_frame convert_to_canfd_frame();
147 * @brief Object representing a can device. Handle opening, closing and reading on the
148 * socket. This is the low level object to be use by can_bus_t.
150 * @params[in] std::string device_name_ - name of the linux device handling the can bus. Generally vcan0, can0, etc.
152 class can_bus_dev_t {
154 std::string device_name_;
157 struct sockaddr_can txAddress_;
159 bool has_can_message_;
160 std::queue <can_message_t> can_message_q_;
162 std::thread th_reading_;
166 can_bus_dev_t(const std::string& dev_name);
168 int open(const struct afb_binding_interface* interface);
171 void start_reading();
172 canfd_frame read(const struct afb_binding_interface *interface);
174 can_message_t next_can_message();
175 void push_new_can_message(const can_message_t& can_msg);
176 bool has_can_message() const;
180 * @brief Object used to handle decoding and manage event queue to be pushed.
182 * @params[in] interface_ - afb_binding_interface pointer to the binder. Used to log messages
183 * @params[in] conf_file_ - configuration file handle used to initialize can_bus_dev_t objects.
187 const struct afb_binding_interface *interface_;
190 std::thread th_decoding_;
191 std::thread th_pushing_;
193 bool has_vehicle_message_;
194 std::queue <openxc_VehicleMessage> vehicle_message_q_;
197 can_bus_t(const struct afb_binding_interface *itf, int& conf_file);
199 std::vector<std::string> read_conf();
201 void start_threads();
203 int send_can_message(can_message_t can_msg);
205 openxc_VehicleMessage& next_vehicle_message();
206 void push_new_vehicle_message(const openxc_VehicleMessage& v_msg);
207 bool has_vehicle_message() const;
211 * @brief A state encoded (SED) signal's mapping from numerical values to
212 * OpenXC state names.
214 * @param[in] in value - The integer value of the state on the CAN bus.
215 * @param[in] char* name - The corresponding string name for the state in OpenXC.
217 struct CanSignalState {
221 typedef struct CanSignalState CanSignalState;
224 * @brief A CAN signal to decode from the bus and output over USB.
226 * @param[in] message - The message this signal is a part of.
227 * @param[in] genericName - The name of the signal to be output over USB.
228 * @param[in] bitPosition - The starting bit of the signal in its CAN message (assuming
229 * non-inverted bit numbering, i.e. the most significant bit of
231 * @param[in] bitSize - The width of the bit field in the CAN message.
232 * @param[in] factor - The final value will be multiplied by this factor. Use 1 if you
233 * don't need a factor.
234 * @param[in] offset - The final value will be added to this offset. Use 0 if you
235 * don't need an offset.
236 * @param[in] minValue - The minimum value for the processed signal.
237 * @param[in] maxValue - The maximum value for the processed signal.
238 * @param[in] frequencyClock - A FrequencyClock struct to control the maximum frequency to
239 * process and send this signal. To process every value, set the
240 * clock's frequency to 0.
241 * @param[in] sendSame - If true, will re-send even if the value hasn't changed.
242 * @param[in] forceSendChanged - If true, regardless of the frequency, it will send the
243 * value if it has changed.
244 * @param[in] states - An array of CanSignalState describing the mapping
245 * between numerical and string values for valid states.
246 * @param[in] stateCount - The length of the states array.
247 * @param[in] writable - True if the signal is allowed to be written from the USB host
248 * back to CAN. Defaults to false.
249 * @param[in] decoder - An optional function to decode a signal from the bus to a human
250 * readable value. If NULL, the default numerical decoder is used.
251 * @param[in] encoder - An optional function to encode a signal value to be written to
252 * CAN into a byte array. If NULL, the default numerical encoder
254 * @param[in] received - True if this signal has ever been received.
255 * @param[in] lastValue - The last received value of the signal. If 'received' is false,
256 * this value is undefined.
259 struct CanMessageDefinition* message;
260 const char* genericName;
267 FrequencyClock frequencyClock;
269 bool forceSendChanged;
270 const CanSignalState* states;
273 SignalDecoder decoder;
274 SignalEncoder encoder;
278 typedef struct CanSignal CanSignal;
281 * @brief The definition of a CAN message. This includes a lot of metadata, so
282 * to save memory this struct should not be used for storing incoming and
283 * outgoing CAN messages.
285 * @param[in] bus - A pointer to the bus this message is on.
286 * @param[in] id - The ID of the message.
287 * @param[in] format - the format of the message's ID.
288 * @param[in] clock - an optional frequency clock to control the output of this
289 * message, if sent raw, or simply to mark the max frequency for custom
290 * handlers to retrieve.
291 * @param[in] forceSendChanged - If true, regardless of the frequency, it will send CAN
292 * message if it has changed when using raw passthrough.
293 * @param[in] lastValue - The last received value of the message. Defaults to undefined.
294 * This is required for the forceSendChanged functionality, as the stack
295 * needs to compare an incoming CAN message with the previous frame.
297 struct CanMessageDefinition {
300 CanMessageFormat format;
301 FrequencyClock frequencyClock;
302 bool forceSendChanged;
303 uint8_t lastValue[CAN_MESSAGE_SIZE];
305 typedef struct CanMessageDefinition CanMessageDefinition;
308 * @brief A parent wrapper for a particular set of CAN messages and associated
309 * CAN buses(e.g. a vehicle or program).
311 * @param[in] index - A numerical ID for the message set, ideally the index in an array
313 * @param[in] name - The name of the message set.
314 * @param[in] busCount - The number of CAN buses defined for this message set.
315 * @param[in] messageCount - The number of CAN messages (across all buses) defined for
317 * @param[in] signalCount - The number of CAN signals (across all messages) defined for
319 * @param[in] commandCount - The number of CanCommmands defined for this message set.
325 unsigned short messageCount;
326 unsigned short signalCount;
327 unsigned short commandCount;
331 * @brief The type signature for a function to handle a custom OpenXC command.
333 * @param[in] char* name - the name of the received command.
334 * @param[in] openxc_DynamicField* value - the value of the received command, in a DynamicField. The actual type
335 * may be a number, string or bool.
336 * @param[in] openxc_DynamicField* event - an optional event from the received command, in a DynamicField. The
337 * actual type may be a number, string or bool.
338 * @param[in] CanSignal* signals - The list of all signals.
339 * @param[in] int signalCount - The length of the signals array.
341 typedef void (*CommandHandler)(const char* name, openxc_DynamicField* value,
342 openxc_DynamicField* event, CanSignal* signals, int signalCount);
344 /* Public: The structure to represent a supported custom OpenXC command.
346 * For completely customized CAN commands without a 1-1 mapping between an
347 * OpenXC message from the host and a CAN signal, you can define the name of the
348 * command and a custom function to handle it in the VI. An example is
349 * the "turn_signal_status" command in OpenXC, which has a value of "left" or
350 * "right". The vehicle may have separate CAN signals for the left and right
351 * turn signals, so you will need to implement a custom command handler to send
352 * the correct signals.
354 * Command handlers are also useful if you want to trigger multiple CAN messages
355 * or signals from a signal OpenXC message.
357 * genericName - The name of the command.
358 * handler - An function to process the received command's data and perform some
362 const char* genericName;
363 CommandHandler handler;
367 * @brief Pre initialize actions made before CAN bus initialization
369 * @param[in] can_bus_dev_t bus - A CanBus struct defining the bus's metadata
370 * @param[in] bool writable - configure the controller in a writable mode. If false, it will be
371 * configured as "listen only" and will not allow writes or even CAN ACKs.
372 * @param[in] buses - An array of all CAN buses.
373 * @param[in] int busCount - The length of the buses array.
375 void pre_initialize(can_bus_dev_t* bus, bool writable, can_bus_dev_t* buses, const int busCount);
377 /* Post-initialize actions made after CAN bus initialization and before the
378 * event loop connection.
380 * bus - A CanBus struct defining the bus's metadata
381 * writable - configure the controller in a writable mode. If false, it will be
382 * configured as "listen only" and will not allow writes or even CAN ACKs.
383 * buses - An array of all CAN buses.
384 * busCount - The length of the buses array.
386 void post_initialize(can_bus_dev_t* bus, bool writable, can_bus_dev_t* buses, const int busCount);
388 /* Public: Check if the device is connected to an active CAN bus, i.e. it's
389 * received a message in the recent past.
391 * Returns true if a message was received on the CAN bus within
392 * CAN_ACTIVE_TIMEOUT_S seconds.
394 bool isBusActive(can_bus_dev_t* bus);
396 /* Public: Log transfer statistics about all active CAN buses to the debug log.
398 * buses - an array of active CAN buses.
399 * busCount - the length of the buses array.
401 void logBusStatistics(can_bus_dev_t* buses, const int busCount);