Handle error in returning a vector by returning
[apps/agl-service-can-low-level.git] / src / can-utils.hpp
1 /*
2  * Copyright (C) 2015, 2016 "IoT.bzh"
3  * Author "Romain Forlot" <romain.forlot@iot.bzh>
4  *
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
8  *
9  *       http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  */
17
18 #pragma once
19
20 #include <map>
21 #include <queue>
22 #include <vector>
23 #include <cstdio>
24 #include <string>
25 #include <thread>
26 #include <fcntl.h>
27 #include <unistd.h>
28 #include <net/if.h>
29 #include <sys/ioctl.h>
30 #include <linux/can.h>
31 #include <sys/socket.h>
32 #include <linux/can/raw.h>
33
34 #include "timer.hpp"
35 #include "openxc.pb.h"
36
37 extern "C"
38 {
39         #include <afb/afb-binding.h>
40         #include <afb/afb-service-itf.h>
41 }
42
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
47
48 #define CAN_MESSAGE_SIZE 8
49
50 #define CAN_ACTIVE_TIMEOUT_S 30
51
52 /**
53  * @brief The type signature for a CAN signal decoder.
54  *
55  * @desc A SignalDecoder transforms a raw floating point CAN signal into a number,
56  * string or boolean.
57  *
58  * @param[in] CanSignal signal - The CAN signal that we are decoding.
59  * @param[in] CanSignal signals - The list of all signals.
60  * @param[in] int signalCount - The length of the signals array.
61  * @param[in] float value - The CAN signal parsed from the message as a raw floating point
62  *      value.
63  * @param[out] bool send - An output parameter. If the decoding failed or the CAN signal should
64  *      not send for some other reason, this should be flipped to false.
65  *
66  * @return a decoded value in an openxc_DynamicField struct.
67  */
68 typedef openxc_DynamicField (*SignalDecoder)(struct CanSignal* signal,
69                 CanSignal* signals, int signalCount, float value, bool* send);
70
71 /**
72  * @brief: The type signature for a CAN signal encoder.
73  *
74  * @desc A SignalEncoder transforms a number, string or boolean into a raw floating
75  * point value that fits in the CAN signal.
76  *
77  * @params[signal] - The CAN signal to encode. 
78  * @params[value] - The dynamic field to encode.
79  * @params[send] - An output parameter. If the encoding failed or the CAN signal should
80  * not be encoded for some other reason, this will be flipped to false.
81  */
82 typedef uint64_t (*SignalEncoder)(struct CanSignal* signal,
83                 openxc_DynamicField* value, bool* send);
84
85 /**
86  * @brief The ID format for a CAN message.
87  *
88  * STANDARD - standard 11-bit CAN arbitration ID.
89  * EXTENDED - an extended frame, with a 29-bit arbitration ID.
90  */
91 enum CanMessageFormat {
92         STANDARD,
93         EXTENDED,
94 };
95 typedef enum CanMessageFormat CanMessageFormat;
96
97 /**
98  * @brief A compact representation of a single CAN message, meant to be used in in/out
99  * buffers.
100  *
101  * param[in] uint32_t id - The ID of the message.
102  * param[in] CanMessageFormat format - the format of the message's ID.
103  * param[in] uint8_t data  - The message's data field.
104  * @param[in] uint8_t length - the length of the data array (max 8).
105 *************************
106 * old CanMessage struct *
107 *************************
108 struct CanMessage {
109         uint32_t id;
110         CanMessageFormat format;
111         uint8_t data[CAN_MESSAGE_SIZE];
112         uint8_t length;
113 };
114 typedef struct CanMessage CanMessage;
115 */
116 class can_message_t {
117         private:
118                 const struct afb_binding_interface *interface_;
119                 uint32_t id_;
120                 CanMessageFormat format_;
121                 uint8_t data_[CAN_MESSAGE_SIZE];
122                 uint8_t length_;
123
124         public:
125                 uint32_t get_id() const;
126                 int get_format() const;
127                 uint8_t get_data() const;
128                 uint8_t get_lenght() const;
129
130                 void set_id(uint32_t id);
131                 void set_format(CanMessageFormat format);
132                 void set_data(uint8_t data);
133                 void set_lenght(uint8_t length);
134
135                 void convert_from_canfd_frame(canfd_frame frame);
136                 canfd_frame convert_to_canfd_frame();
137 };
138
139 /** 
140  * @brief Object representing a can device. Handle opening, closing and reading on the
141  * socket. This is the low level object to be use by can_bus_t.
142  *
143  * @params[in] std::string device_name_ - name of the linux device handling the can bus. Generally vcan0, can0, etc.
144  */
145 class can_bus_dev_t {
146         private:
147                 std::string device_name_;
148                 int can_socket_;
149                 bool is_fdmode_on_;
150                 struct sockaddr_can txAddress_;
151
152                 bool has_can_message_;
153                 std::queue <can_message_t> can_message_q_;
154
155                 std::thread th_reading_;
156                 bool is_running_;
157
158         public:
159                 can_bus_dev_t(const std::string& dev_name);
160
161                 int open(const struct afb_binding_interface* interface);
162                 int close();
163                 bool is_running();
164                 void start_reading();
165                 canfd_frame read(const struct afb_binding_interface *interface);
166                 
167                 can_message_t next_can_message();
168                 void push_new_can_message(const can_message_t& can_msg);                
169                 bool has_can_message() const;
170 };
171
172 /** 
173  * @brief Object used to handle decoding and manage event queue to be pushed.
174  *
175  * @params[in] interface_ - afb_binding_interface pointer to the binder. Used to log messages
176  * @params[in] conf_file_ - configuration file handle used to initialize can_bus_dev_t objects.
177  */
178 class can_bus_t {
179         private:
180                 const struct afb_binding_interface *interface_;
181                 int conf_file_;
182                 
183                 std::thread th_decoding_;
184                 std::thread th_pushing_;
185
186                 bool has_vehicle_message_;
187                 std::queue <openxc_VehicleMessage> vehicle_message_q_;
188
189         public:
190                 can_bus_t(const struct afb_binding_interface *itf, int& conf_file);
191                 int init_can_dev();
192                 std::vector<std::string> read_conf();
193                 
194                 void start_threads();
195                 
196                 int send_can_message(can_message_t can_msg);
197
198                 openxc_VehicleMessage& next_vehicle_message();
199                 void push_new_vehicle_message(const openxc_VehicleMessage& v_msg);
200                 bool has_vehicle_message() const;
201 };
202
203 /**
204  * @brief A state encoded (SED) signal's mapping from numerical values to
205  * OpenXC state names.
206  *
207  * @param[in] in value - The integer value of the state on the CAN bus.
208  * @param[in] char* name  - The corresponding string name for the state in OpenXC.
209  */
210 struct CanSignalState {
211         const int value;
212         const char* name;
213 };
214 typedef struct CanSignalState CanSignalState;
215
216 /**
217  * @brief A CAN signal to decode from the bus and output over USB.
218  *
219  * @param[in] message      - The message this signal is a part of.
220  * @param[in] genericName - The name of the signal to be output over USB.
221  * @param[in] bitPosition - The starting bit of the signal in its CAN message (assuming
222  *                               non-inverted bit numbering, i.e. the most significant bit of
223  *                               each byte is 0)
224  * @param[in] bitSize      - The width of the bit field in the CAN message.
225  * @param[in] factor       - The final value will be multiplied by this factor. Use 1 if you
226  *                               don't need a factor.
227  * @param[in] offset       - The final value will be added to this offset. Use 0 if you
228  *                               don't need an offset.
229  * @param[in] minValue    - The minimum value for the processed signal.
230  * @param[in] maxValue    - The maximum value for the processed signal.
231  * @param[in] frequencyClock - A FrequencyClock struct to control the maximum frequency to
232  *                              process and send this signal. To process every value, set the
233  *                              clock's frequency to 0.
234  * @param[in] sendSame    - If true, will re-send even if the value hasn't changed.
235  * @param[in] forceSendChanged - If true, regardless of the frequency, it will send the
236  *                              value if it has changed.
237  * @param[in] states       - An array of CanSignalState describing the mapping
238  *                               between numerical and string values for valid states.
239  * @param[in] stateCount  - The length of the states array.
240  * @param[in] writable    - True if the signal is allowed to be written from the USB host
241  *                               back to CAN. Defaults to false.
242  * @param[in] decoder      - An optional function to decode a signal from the bus to a human
243  *                              readable value. If NULL, the default numerical decoder is used.
244  * @param[in] encoder      - An optional function to encode a signal value to be written to
245  *                                CAN into a byte array. If NULL, the default numerical encoder
246  *                                is used.
247  * @param[in] received    - True if this signal has ever been received.
248  * @param[in] lastValue   - The last received value of the signal. If 'received' is false,
249  *              this value is undefined.
250  */
251 struct CanSignal {
252         struct CanMessageDefinition* message;
253         const char* genericName;
254         uint8_t bitPosition;
255         uint8_t bitSize;
256         float factor;
257         float offset;
258         float minValue;
259         float maxValue;
260         FrequencyClock frequencyClock;
261         bool sendSame;
262         bool forceSendChanged;
263         const CanSignalState* states;
264         uint8_t stateCount;
265         bool writable;
266         SignalDecoder decoder;
267         SignalEncoder encoder;
268         bool received;
269         float lastValue;
270 };
271 typedef struct CanSignal CanSignal;
272
273 /**
274  * @brief The definition of a CAN message. This includes a lot of metadata, so
275  * to save memory this struct should not be used for storing incoming and
276  * outgoing CAN messages.
277  *
278  * @param[in] bus - A pointer to the bus this message is on.
279  * @param[in] id - The ID of the message.
280  * @param[in] format - the format of the message's ID.
281  * @param[in] clock - an optional frequency clock to control the output of this
282  *              message, if sent raw, or simply to mark the max frequency for custom
283  *              handlers to retrieve.
284  * @param[in] forceSendChanged - If true, regardless of the frequency, it will send CAN
285  *              message if it has changed when using raw passthrough.
286  * @param[in] lastValue - The last received value of the message. Defaults to undefined.
287  *              This is required for the forceSendChanged functionality, as the stack
288  *              needs to compare an incoming CAN message with the previous frame.
289  */
290 struct CanMessageDefinition {
291         struct CanBus* bus;
292         uint32_t id;
293         CanMessageFormat format;
294         FrequencyClock frequencyClock;
295         bool forceSendChanged;
296         uint8_t lastValue[CAN_MESSAGE_SIZE];
297 };
298 typedef struct CanMessageDefinition CanMessageDefinition;
299
300 /**
301  * @brief A parent wrapper for a particular set of CAN messages and associated
302  *      CAN buses(e.g. a vehicle or program).
303  *
304  *      @param[in] index - A numerical ID for the message set, ideally the index in an array
305  *              for fast lookup
306  *      @param[in] name - The name of the message set.
307  *      @param[in] busCount - The number of CAN buses defined for this message set.
308  *      @param[in] messageCount - The number of CAN messages (across all buses) defined for
309  *              this message set.
310  *      @param[in] signalCount - The number of CAN signals (across all messages) defined for
311  *              this message set.
312  *      @param[in] commandCount - The number of CanCommmands defined for this message set.
313  */
314  typedef struct {
315         uint8_t index;
316         const char* name;
317         uint8_t busCount;
318         unsigned short messageCount;
319         unsigned short signalCount;
320         unsigned short commandCount;
321 } CanMessageSet;
322
323 /**
324  * @brief The type signature for a function to handle a custom OpenXC command.
325  *
326  * @param[in] char* name - the name of the received command.
327  * @param[in] openxc_DynamicField* value - the value of the received command, in a DynamicField. The actual type
328  *              may be a number, string or bool.
329  * @param[in] openxc_DynamicField* event - an optional event from the received command, in a DynamicField. The
330  *              actual type may be a number, string or bool.
331  * @param[in] CanSignal* signals - The list of all signals.
332  * @param[in] int signalCount - The length of the signals array.
333  */
334 typedef void (*CommandHandler)(const char* name, openxc_DynamicField* value,
335                 openxc_DynamicField* event, CanSignal* signals, int signalCount);
336
337 /* Public: The structure to represent a supported custom OpenXC command.
338  *
339  * For completely customized CAN commands without a 1-1 mapping between an
340  * OpenXC message from the host and a CAN signal, you can define the name of the
341  * command and a custom function to handle it in the VI. An example is
342  * the "turn_signal_status" command in OpenXC, which has a value of "left" or
343  * "right". The vehicle may have separate CAN signals for the left and right
344  * turn signals, so you will need to implement a custom command handler to send
345  * the correct signals.
346  *
347  * Command handlers are also useful if you want to trigger multiple CAN messages
348  * or signals from a signal OpenXC message.
349  *
350  * genericName - The name of the command.
351  * handler - An function to process the received command's data and perform some
352  *              action.
353  */
354 typedef struct {
355         const char* genericName;
356         CommandHandler handler;
357 } CanCommand;
358
359 /**
360  * @brief Pre initialize actions made before CAN bus initialization
361  *
362  * @param[in] can_bus_dev_t bus - A CanBus struct defining the bus's metadata
363  * @param[in] bool writable - configure the controller in a writable mode. If false, it will be
364  *              configured as "listen only" and will not allow writes or even CAN ACKs.
365  * @param[in] buses - An array of all CAN buses.
366  * @param[in] int busCount - The length of the buses array.
367  */
368 void pre_initialize(can_bus_dev_t* bus, bool writable, can_bus_dev_t* buses, const int busCount);
369
370 /* Post-initialize actions made after CAN bus initialization and before the
371  * event loop connection.
372  *
373  * bus - A CanBus struct defining the bus's metadata
374  * writable - configure the controller in a writable mode. If false, it will be
375  *              configured as "listen only" and will not allow writes or even CAN ACKs.
376  * buses - An array of all CAN buses.
377  * busCount - The length of the buses array.
378  */
379 void post_initialize(can_bus_dev_t* bus, bool writable, can_bus_dev_t* buses, const int busCount);
380
381 /* Public: Check if the device is connected to an active CAN bus, i.e. it's
382  * received a message in the recent past.
383  *
384  * Returns true if a message was received on the CAN bus within
385  * CAN_ACTIVE_TIMEOUT_S seconds.
386  */
387 bool isBusActive(can_bus_dev_t* bus);
388
389 /* Public: Log transfer statistics about all active CAN buses to the debug log.
390  *
391  * buses - an array of active CAN buses.
392  * busCount - the length of the buses array.
393  */
394 void logBusStatistics(can_bus_dev_t* buses, const int busCount);
395
396 /**
397  * @brief Function representing thread activated by can bus objects
398  */
399 void can_reader(can_bus_dev_t& can_bus);
400 void can_decode_message(can_bus_t& can_bus);
401 void can_event_push(can_bus_t& can_bus);