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.
26 #include <linux/can.h>
29 #include "openxc.pb.h"
30 #include <afb/afb-binding.h>
31 #include <afb/afb-service-itf.h>
33 // TODO actual max is 32 but dropped to 24 for memory considerations
34 #define MAX_ACCEPTANCE_FILTERS 24
35 // TODO this takes up a ton of memory
36 #define MAX_DYNAMIC_MESSAGE_COUNT 12
38 #define CAN_MESSAGE_SIZE 8
40 #define CAN_ACTIVE_TIMEOUT_S 30
43 * @brief The type signature for a CAN signal decoder.
45 * @desc A SignalDecoder transforms a raw floating point CAN signal into a number,
48 * @param[in] CanSignal signal - The CAN signal that we are decoding.
49 * @param[in] CanSignal signals - The list of all signals.
50 * @param[in] int signalCount - The length of the signals array.
51 * @param[in] float value - The CAN signal parsed from the message as a raw floating point
53 * @param[out] bool send - An output parameter. If the decoding failed or the CAN signal should
54 * not send for some other reason, this should be flipped to false.
56 * @return a decoded value in an openxc_DynamicField struct.
58 typedef openxc_DynamicField (*SignalDecoder)(struct CanSignal* signal,
59 CanSignal* signals, int signalCount, float value, bool* send);
62 * @brief: The type signature for a CAN signal encoder.
64 * @desc A SignalEncoder transforms a number, string or boolean into a raw floating
65 * point value that fits in the CAN signal.
67 * @params[signal] - The CAN signal to encode.
68 * @params[value] - The dynamic field to encode.
69 * @params[send] - An output parameter. If the encoding failed or the CAN signal should
70 * not be encoded for some other reason, this will be flipped to false.
72 typedef uint64_t (*SignalEncoder)(struct CanSignal* signal,
73 openxc_DynamicField* value, bool* send);
76 * @brief The ID format for a CAN message.
78 * STANDARD - standard 11-bit CAN arbitration ID.
79 * EXTENDED - an extended frame, with a 29-bit arbitration ID.
81 enum CanMessageFormat {
85 typedef enum CanMessageFormat CanMessageFormat;
88 * @brief A compact representation of a single CAN message, meant to be used in in/out
91 * param[in] uint32_t id - The ID of the message.
92 * param[in] CanMessageFormat format - the format of the message's ID.
93 * param[in] uint8_t data - The message's data field.
94 * @param[in] uint8_t length - the length of the data array (max 8).
95 *************************
96 * old CanMessage struct *
97 *************************
100 CanMessageFormat format;
101 uint8_t data[CAN_MESSAGE_SIZE];
104 typedef struct CanMessage CanMessage;
106 class can_message_t {
108 const struct afb_binding_interface *interface_;
110 CanMessageFormat format_;
111 uint8_t data_[CAN_MESSAGE_SIZE];
115 uint32_t get_id() const;
116 int get_format() const;
117 uint8_t get_data() const;
118 uint8_t get_lenght() const;
120 void set_id(uint32_t id);
121 void set_format(CanMessageFormat format);
122 void set_data(uint8_t data);
123 void set_lenght(uint8_t length);
125 void convert_from_canfd_frame(canfd_frame frame);
126 canfd_frame convert_to_canfd_frame();
130 * @brief Object representing a can device. Handle opening, closing and reading on the
131 * socket. This is the low level object to be use by can_bus_t.
133 * @params[in] std::string device_name_ - name of the linux device handling the can bus. Generally vcan0, can0, etc.
135 class can_bus_dev_t {
137 std::string device_name_;
140 struct sockaddr_can txAddress_;
142 bool has_can_message_;
143 std::queue <can_message_t> can_message_q_;
145 std::thread th_reading_;
149 can_bus_dev_t(const std::string& dev_name);
155 can_message_t* next_can_message();
156 void push_new_can_message(const can_message_t& can_msg);
157 bool has_can_message() const;
161 * @brief Object used to handle decoding and manage event queue to be pushed.
163 * @params[in] interface_ - afb_binding_interface pointer to the binder. Used to log messages
164 * @params[in] conf_file_ - configuration file handle used to initialize can_bus_dev_t objects.
168 const struct afb_binding_interface *interface_;
171 std::thread th_decoding_;
172 std::thread th_pushing_;
174 bool has_vehicle_message_;
175 std::queue <openxc_VehicleMessage> vehicle_message_q_;
178 can_bus_t(const struct afb_binding_interface *itf, int& conf_file);
180 std::vector<std::string> read_conf();
182 void start_threads();
184 int send_can_message(can_message_t can_msg);
186 openxc_VehicleMessage& next_vehicle_message();
187 void push_new_vehicle_message(const openxc_VehicleMessage& v_msg);
188 bool has_vehicle_message() const;
192 * @brief A state encoded (SED) signal's mapping from numerical values to
193 * OpenXC state names.
195 * @param[in] in value - The integer value of the state on the CAN bus.
196 * @param[in] char* name - The corresponding string name for the state in OpenXC.
198 struct CanSignalState {
202 typedef struct CanSignalState CanSignalState;
205 * @brief A CAN signal to decode from the bus and output over USB.
207 * @param[in] message - The message this signal is a part of.
208 * @param[in] genericName - The name of the signal to be output over USB.
209 * @param[in] bitPosition - The starting bit of the signal in its CAN message (assuming
210 * non-inverted bit numbering, i.e. the most significant bit of
212 * @param[in] bitSize - The width of the bit field in the CAN message.
213 * @param[in] factor - The final value will be multiplied by this factor. Use 1 if you
214 * don't need a factor.
215 * @param[in] offset - The final value will be added to this offset. Use 0 if you
216 * don't need an offset.
217 * @param[in] minValue - The minimum value for the processed signal.
218 * @param[in] maxValue - The maximum value for the processed signal.
219 * @param[in] frequencyClock - A FrequencyClock struct to control the maximum frequency to
220 * process and send this signal. To process every value, set the
221 * clock's frequency to 0.
222 * @param[in] sendSame - If true, will re-send even if the value hasn't changed.
223 * @param[in] forceSendChanged - If true, regardless of the frequency, it will send the
224 * value if it has changed.
225 * @param[in] states - An array of CanSignalState describing the mapping
226 * between numerical and string values for valid states.
227 * @param[in] stateCount - The length of the states array.
228 * @param[in] writable - True if the signal is allowed to be written from the USB host
229 * back to CAN. Defaults to false.
230 * @param[in] decoder - An optional function to decode a signal from the bus to a human
231 * readable value. If NULL, the default numerical decoder is used.
232 * @param[in] encoder - An optional function to encode a signal value to be written to
233 * CAN into a byte array. If NULL, the default numerical encoder
235 * @param[in] received - True if this signal has ever been received.
236 * @param[in] lastValue - The last received value of the signal. If 'received' is false,
237 * this value is undefined.
240 struct CanMessageDefinition* message;
241 const char* genericName;
248 FrequencyClock frequencyClock;
250 bool forceSendChanged;
251 const CanSignalState* states;
254 SignalDecoder decoder;
255 SignalEncoder encoder;
259 typedef struct CanSignal CanSignal;
262 * @brief The definition of a CAN message. This includes a lot of metadata, so
263 * to save memory this struct should not be used for storing incoming and
264 * outgoing CAN messages.
266 * @param[in] bus - A pointer to the bus this message is on.
267 * @param[in] id - The ID of the message.
268 * @param[in] format - the format of the message's ID.
269 * @param[in] clock - an optional frequency clock to control the output of this
270 * message, if sent raw, or simply to mark the max frequency for custom
271 * handlers to retrieve.
272 * @param[in] forceSendChanged - If true, regardless of the frequency, it will send CAN
273 * message if it has changed when using raw passthrough.
274 * @param[in] lastValue - The last received value of the message. Defaults to undefined.
275 * This is required for the forceSendChanged functionality, as the stack
276 * needs to compare an incoming CAN message with the previous frame.
278 struct CanMessageDefinition {
281 CanMessageFormat format;
282 FrequencyClock frequencyClock;
283 bool forceSendChanged;
284 uint8_t lastValue[CAN_MESSAGE_SIZE];
286 typedef struct CanMessageDefinition CanMessageDefinition;
288 /* Private: An entry in the list of acceptance filters for each CanBus.
290 * This struct is meant to be used with a LIST type from <sys/queue.h>.
292 * filter - the value for the CAN acceptance filter.
293 * activeUserCount - The number of active consumers of this filter's messages.
294 * When 0, this filter can be removed.
295 * format - the format of the ID for the filter.
296 struct AcceptanceFilterListEntry {
298 uint8_t activeUserCount;
299 CanMessageFormat format;
300 LIST_ENTRY(AcceptanceFilterListEntry) entries;
304 /* Private: A type of list containing CAN acceptance filters.
305 LIST_HEAD(AcceptanceFilterList, AcceptanceFilterListEntry);
307 struct CanMessageDefinitionListEntry {
308 CanMessageDefinition definition;
309 LIST_ENTRY(CanMessageDefinitionListEntry) entries;
311 LIST_HEAD(CanMessageDefinitionList, CanMessageDefinitionListEntry);
315 * @brief A parent wrapper for a particular set of CAN messages and associated
316 * CAN buses(e.g. a vehicle or program).
318 * @param[in] index - A numerical ID for the message set, ideally the index in an array
320 * @param[in] name - The name of the message set.
321 * @param[in] busCount - The number of CAN buses defined for this message set.
322 * @param[in] messageCount - The number of CAN messages (across all buses) defined for
324 * @param[in] signalCount - The number of CAN signals (across all messages) defined for
326 * @param[in] commandCount - The number of CanCommmands defined for this message set.
332 unsigned short messageCount;
333 unsigned short signalCount;
334 unsigned short commandCount;
338 * @brief The type signature for a function to handle a custom OpenXC command.
340 * @param[in] char* name - the name of the received command.
341 * @param[in] openxc_DynamicField* value - the value of the received command, in a DynamicField. The actual type
342 * may be a number, string or bool.
343 * @param[in] openxc_DynamicField* event - an optional event from the received command, in a DynamicField. The
344 * actual type may be a number, string or bool.
345 * @param[in] CanSignal* signals - The list of all signals.
346 * @param[in] int signalCount - The length of the signals array.
348 typedef void (*CommandHandler)(const char* name, openxc_DynamicField* value,
349 openxc_DynamicField* event, CanSignal* signals, int signalCount);
351 /* Public: The structure to represent a supported custom OpenXC command.
353 * For completely customized CAN commands without a 1-1 mapping between an
354 * OpenXC message from the host and a CAN signal, you can define the name of the
355 * command and a custom function to handle it in the VI. An example is
356 * the "turn_signal_status" command in OpenXC, which has a value of "left" or
357 * "right". The vehicle may have separate CAN signals for the left and right
358 * turn signals, so you will need to implement a custom command handler to send
359 * the correct signals.
361 * Command handlers are also useful if you want to trigger multiple CAN messages
362 * or signals from a signal OpenXC message.
364 * genericName - The name of the command.
365 * handler - An function to process the received command's data and perform some
369 const char* genericName;
370 CommandHandler handler;
374 * @brief Pre initialize actions made before CAN bus initialization
376 * @param[in] can_bus_dev_t bus - A CanBus struct defining the bus's metadata
377 * @param[in] bool writable - configure the controller in a writable mode. If false, it will be
378 * configured as "listen only" and will not allow writes or even CAN ACKs.
379 * @param[in] buses - An array of all CAN buses.
380 * @param[in] int busCount - The length of the buses array.
382 void pre_initialize(can_bus_dev_t* bus, bool writable, CanBus* buses, const int busCount);
384 /* Post-initialize actions made after CAN bus initialization and before the
385 * event loop connection.
387 * bus - A CanBus struct defining the bus's metadata
388 * writable - configure the controller in a writable mode. If false, it will be
389 * configured as "listen only" and will not allow writes or even CAN ACKs.
390 * buses - An array of all CAN buses.
391 * busCount - The length of the buses array.
393 void post_initialize(can_bus_dev_t* bus, bool writable, CanBus* buses, const int busCount);
395 /* Public: Check if the device is connected to an active CAN bus, i.e. it's
396 * received a message in the recent past.
398 * Returns true if a message was received on the CAN bus within
399 * CAN_ACTIVE_TIMEOUT_S seconds.
401 bool isBusActive(can_bus_dev_t* bus);
403 /* Public: Log transfer statistics about all active CAN buses to the debug log.
405 * buses - an array of active CAN buses.
406 * busCount - the length of the buses array.
408 void logBusStatistics(CanBus* buses, const int busCount);