Improve doxygen comments
[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 <json-c/json.h>
33 #include <linux/can/raw.h>
34
35 #include "timer.hpp"
36 #include "openxc.pb.h"
37
38 extern "C"
39 {
40         #include <afb/afb-binding.h>
41         #include <afb/afb-service-itf.h>
42 }
43
44 // TODO actual max is 32 but dropped to 24 for memory considerations
45 #define MAX_ACCEPTANCE_FILTERS 24
46 // TODO this takes up a ton of memory
47 #define MAX_DYNAMIC_MESSAGE_COUNT 12
48
49 #define CAN_MESSAGE_SIZE 8
50
51 #define CAN_ACTIVE_TIMEOUT_S 30
52
53 /**
54  * @brief The type signature for a CAN signal decoder.
55  *
56  * @desc A SignalDecoder transforms a raw floating point CAN signal into a number,
57  * string or boolean.
58  *
59  * @param[in] CanSignal signal - The CAN signal that we are decoding.
60  * @param[in] CanSignal signals - The list of all signals.
61  * @param[in] int signalCount - The length of the signals array.
62  * @param[in] float value - The CAN signal parsed from the message as a raw floating point
63  *      value.
64  * @param[out] bool send - An output parameter. If the decoding failed or the CAN signal should
65  *      not send for some other reason, this should be flipped to false.
66  *
67  * @return a decoded value in an openxc_DynamicField struct.
68  */
69 typedef openxc_DynamicField (*SignalDecoder)(struct CanSignal* signal,
70                 CanSignal* signals, int signalCount, float value, bool* send);
71
72 /**
73  * @brief: The type signature for a CAN signal encoder.
74  *
75  * @desc A SignalEncoder transforms a number, string or boolean into a raw floating
76  * point value that fits in the CAN signal.
77  *
78  * @params[signal] - The CAN signal to encode. 
79  * @params[value] - The dynamic field to encode.
80  * @params[send] - An output parameter. If the encoding failed or the CAN signal should
81  * not be encoded for some other reason, this will be flipped to false.
82  */
83 typedef uint64_t (*SignalEncoder)(struct CanSignal* signal,
84                 openxc_DynamicField* value, bool* send);
85
86 /**
87  * @enum CanMessageFormat
88  * @brief The ID format for a CAN message.
89  */
90 enum CanMessageFormat {
91         STANDARD, /*!< STANDARD - standard 11-bit CAN arbitration ID. */
92         EXTENDED, /*!< EXTENDED - an extended frame, with a 29-bit arbitration ID. */
93         ERROR,    /*!< ERROR - ERROR code used at initialization to signify that it isn't usable'*/
94 };
95 typedef enum CanMessageFormat CanMessageFormat;
96
97 /**
98  * @class can_message_t
99  *
100  * @brief A compact representation of a single CAN message, meant to be used in in/out
101  * buffers.
102  *
103  * param[in] 
104  * param[in] 
105  * param[in] 
106  * @param[in]
107  */
108
109 /*************************
110  * old CanMessage struct *
111  *************************
112 struct CanMessage {
113         uint32_t id;
114         CanMessageFormat format;
115         uint8_t data[CAN_MESSAGE_SIZE];
116         uint8_t length;
117 };
118 typedef struct CanMessage CanMessage;
119 */
120 class can_message_t {
121         private:
122                 const struct afb_binding_interface* interface_; /*!< afb_binding_interface interface between daemon and binding */ 
123
124                 uint32_t id_; /*!< uint32_t id - The ID of the message. */
125                 uint8_t length_; /*!<  uint8_t length - the length of the data array (max 8). */
126                 CanMessageFormat format_; /*!< CanMessageFormat format - the format of the message's ID.*/
127                 uint8_t data_[CAN_MESSAGE_SIZE]; /*!< uint8_t data  - The message's data field with a size of 8 which is the standard about CAN bus messages.*/
128
129         public:
130                 /**
131                  * @brief Class constructor
132                  *
133                  * Constructor about can_message_t class.
134                  *
135                  * @param interface - const structafb_binding_interface pointer
136                  */
137                 can_message_t(const struct afb_binding_interface* interface);
138
139                 /**
140                  * @brief Retrieve id_ member value.
141                  *
142                  * @return uint32_t id_ class member
143                  */
144                 uint32_t get_id() const;
145                 
146                 /**
147                  * @brief Retrieve format_ member value.
148                  *
149                  * @return CanMessageFormat format_ class member
150                  */
151                 int get_format() const;
152                 
153                 /**
154                  * @brief Retrieve data_ member value.
155                  *
156                  * @return uint8_t data_ pointer class member
157                  */
158                 const uint8_t* get_data() const;
159                 
160                 /**
161                  * @brief Retrieve length_ member value.
162                  *
163                  * @return uint8_t length_ class member
164                  */
165                 uint8_t get_length() const;
166
167                 /**
168                  * @brief Control whether the object is correctly initialized
169                  *  to be sent over the CAN bus
170                  *
171                  * @return true if object correctly initialized and false if not...
172                  */
173                 bool is_correct_to_send();
174                 
175                 /**
176                  * @brief Set id_ member value.
177                  *
178                  * Preferred way to initialize these members by using 
179                  * convert_from_canfd_frame method.
180                  *
181                  * @param uint32_t id_ class member
182                  */
183                 void set_id(const uint32_t new_id);
184                 
185                 /**
186                  * @brief Set format_ member value.
187                  *
188                  * Preferred way to initialize these members by using 
189                  * convert_from_canfd_frame method.
190                  *
191                  * @param CanMessageFormat format_ class member
192                  */
193                 void set_format(const CanMessageFormat format);
194                 
195                 /**
196                  * @brief Set data_ member value.
197                  *
198                  * Preferred way to initialize these members by using 
199                  * convert_from_canfd_frame method.
200                  *
201                  * @param uint8_t data_ array with a max size of 8 elements.
202                  */
203                 void set_data(const uint8_t new_data);
204                 
205                 /**
206                  * @brief Set length_ member value.
207                  *
208                  * Preferred way to initialize these members by using 
209                  * convert_from_canfd_frame method.
210                  *
211                  * @param uint8_t length_ array with a max size of 8 elements.
212                  */
213                 void set_length(const uint8_t new_length);
214
215                 /**
216                  * @brief Take a canfd_frame struct to initialize class members
217                  *
218                  * This is the preferred way to initialize class members.
219                  *
220                  * @param canfd_frame struct read from can bus device.
221                  */
222                 void convert_from_canfd_frame(const canfd_frame& frame);
223                 
224                 /**
225                  * @brief Take all initialized class's members and build an 
226                  * canfd_frame struct that can be use to send a CAN message over
227                  * the bus.
228                  *
229                  * @return canfd_frame struct built from class members.
230                  */
231                 canfd_frame convert_to_canfd_frame();
232 };
233
234 /** 
235  * @class can_bus_t
236  * @brief Object used to handle decoding and manage event queue to be pushed.
237  *
238  * This object is also used to initialize can_bus_dev_t object after reading 
239  * json conf file describing the CAN devices to use. Thus, those object will read 
240  * on the device the CAN frame and push them into the can_bus_t can_message_q_ queue.
241  *
242  * That queue will be later used to be decoded and pushed to subscribers.
243  */
244 class can_bus_t {
245         private:
246                 int conf_file_; /*!< conf_file_ - configuration file handle used to initialize can_bus_dev_t objects.*/
247                 
248                 std::thread th_decoding_; /*!< thread that'll handle decoding a can frame */
249                 std::thread th_pushing_; /*!<  thread that'll handle pushing decoded can frame to subscribers */
250
251                 bool has_can_message_; /*!< boolean members that control whether or not there is can_message into the queue */
252                 std::queue <can_message_t> can_message_q_; /*!< queue that'll store can_message_t to decoded */
253
254                 bool has_vehicle_message_; /*!< boolean members that control whether or not there is openxc_VehicleMessage into the queue */
255                 std::queue <openxc_VehicleMessage> vehicle_message_q_; /*!< queue that'll store openxc_VehicleMessage to pushed */
256
257         public:
258                 const struct afb_binding_interface *interface_; /*!< interface_ - afb_binding_interface pointer to the binder. Used to log messages */
259
260                 /**
261                  * @brief Class constructor
262                  *
263                  * @param struct afb_binding_interface *interface between daemon and binding
264                  * @param int file handle to the json configuration file.
265                  */
266                 can_bus_t(const struct afb_binding_interface *interface, int& conf_file);
267                 
268                 /**
269                  * @brief Will initialize can_bus_dev_t objects after reading 
270                  * the configuration file passed in the constructor.
271                  */
272                 int init_can_dev();
273                 
274                 /**
275                  * @brief read the conf_file_ and will parse json objects
276                  * in it searching for canbus objects devices name.
277                  *
278                  * @return Vector of can bus device name string.
279                  */
280                  std::vector<std::string> read_conf();
281                 
282                 /**
283                  * @brief Will initialize threads that will decode
284                  *  and push subscribed events.
285                  */
286                 void start_threads();
287
288                 /**
289                  * @brief Return first can_message_t on the queue 
290                  *
291                  * @return a can_message_t 
292                  */
293                 can_message_t next_can_message();
294                 
295                 /**
296                  * @brief Push a can_message_t into the queue
297                  *
298                  * @param the const reference can_message_t object to push into the queue
299                  */
300                 void push_new_can_message(const can_message_t& can_msg);                
301                 
302                 /**
303                  * @brief Return a boolean telling if there is any can_message into the queue
304                  *
305                  * @return true if there is at least a can_message_t, false if not.
306                  */
307                 bool has_can_message() const;
308                 
309                 /**
310                  * @brief Return first openxc_VehicleMessage on the queue 
311                  *
312                  * @return a openxc_VehicleMessage containing a decoded can message
313                  */
314                 openxc_VehicleMessage next_vehicle_message();
315                 
316                 /**
317                  * @brief Push a openxc_VehicleMessage into the queue
318                  *
319                  * @param the const reference openxc_VehicleMessage object to push into the queue
320                  */
321                 void push_new_vehicle_message(const openxc_VehicleMessage& v_msg);
322                 
323                 /**
324                  * @brief Return a boolean telling if there is any openxc_VehicleMessage into the queue
325                  *
326                  * @return true if there is at least a openxc_VehicleMessage, false if not.
327                  */
328                 bool has_vehicle_message() const;
329 };
330
331 /**
332  * @class can_bus_dev_t 
333  *
334  * @brief Object representing a can device. Handle opening, closing and reading on the
335  *  socket. This is the low level object to be use by can_bus_t.
336  */
337 class can_bus_dev_t {
338         private:
339                 std::string device_name_; /*!< std::string device_name_ - name of the linux device handling the can bus. Generally vcan0, can0, etc. */
340                 int can_socket_; /*!< socket handler for the can device */
341                 bool is_fdmode_on_; /*!< boolean telling if whether or not the can socket use fdmode. */
342                 struct sockaddr_can txAddress_; /*!< internal member using to bind to the socket */
343
344                 std::thread th_reading_; /*!< Thread handling read the socket can device filling can_message_q_ queue of can_bus_t */
345                 bool is_running_; /*!< boolean telling whether or not reading is running or not */
346
347         public:
348                 /**
349                  * @brief Class constructor 
350                  * 
351                  * @param const string representing the device name into the linux /dev tree
352                  */
353                 can_bus_dev_t(const std::string& dev_name);
354
355                 /**
356                  * @brief Open the can socket and returning it 
357                  *
358                  * @return 
359                  */
360                 int open(const struct afb_binding_interface* interface);
361                 int close();
362                 bool is_running();
363                 
364                 /**
365                 * @brief start reading threads and set flag is_running_
366                 *
367                 * @param can_bus_t reference can_bus_t. it will be passed to the thread 
368                 *  to allow using afb_binding_interface and can_bus_t queue.
369                 */
370                 void start_reading(can_bus_t& can_bus);
371
372                 /**
373                 * @brief Read the can socket and retrieve canfd_frame
374                 *
375                 * @param const struct afb_binding_interface* interface pointer. Used to be able to log 
376                 *  using application framework logger.
377                 */
378                 canfd_frame read(const struct afb_binding_interface *interface);
379                 
380                 /**
381                 * @brief Send a can message from a can_message_t object.
382                 * 
383                 * @param const can_message_t& can_msg: the can message object to send 
384                 * @param const struct afb_binding_interface* interface pointer. Used to be able to log 
385                 *  using application framework logger.
386                 */
387                 int send_can_message(can_message_t& can_msg, const struct afb_binding_interface* interface);
388 };
389
390 /**
391  * @struct CanSignalState
392  *
393  * @brief A state encoded (SED) signal's mapping from numerical values to
394  * OpenXC state names.
395  */
396 struct CanSignalState {
397         const int value; /*!< int value - The integer value of the state on the CAN bus.*/
398         const char* name; /*!< char* name  - The corresponding string name for the state in OpenXC. */
399 };
400 typedef struct CanSignalState CanSignalState;
401
402 /**
403  * @struct CanSignal
404  *
405  * @brief A CAN signal to decode from the bus and output over USB.
406  */
407 struct CanSignal {
408         struct CanMessageDefinition* message; /*!< message         - The message this signal is a part of. */
409         const char* genericName; /*!< genericName - The name of the signal to be output over USB.*/
410         uint8_t bitPosition; /*!< bitPosition - The starting bit of the signal in its CAN message (assuming
411                                                 *       non-inverted bit numbering, i.e. the most significant bit of
412                                                 *       each byte is 0) */
413         uint8_t bitSize; /*!< bitSize - The width of the bit field in the CAN message. */
414         float factor; /*!< factor - The final value will be multiplied by this factor. Use 1 if you
415                                 *       don't need a factor. */
416         float offset; /*!< offset          - The final value will be added to this offset. Use 0 if you
417                                 *       don't need an offset. */
418         float minValue; /*!< minValue    - The minimum value for the processed signal.*/
419         float maxValue; /*!< maxValue    - The maximum value for the processed signal. */
420         FrequencyClock frequencyClock; /*!< frequencyClock - A FrequencyClock struct to control the maximum frequency to
421                                                                 *       process and send this signal. To process every value, set the
422                                                                 *       clock's frequency to 0. */
423         bool sendSame; /*!< sendSame    - If true, will re-send even if the value hasn't changed.*/
424         bool forceSendChanged; /*!< forceSendChanged - If true, regardless of the frequency, it will send the
425                                                 *       value if it has changed. */
426         const CanSignalState* states; /*!< states          - An array of CanSignalState describing the mapping
427                                                                 *       between numerical and string values for valid states. */
428         uint8_t stateCount; /*!< stateCount  - The length of the states array. */
429         bool writable; /*!< writable    - True if the signal is allowed to be written from the USB host
430                                 *       back to CAN. Defaults to false.*/
431         SignalDecoder decoder; /*!< decoder        - An optional function to decode a signal from the bus to a human
432                                                 *       readable value. If NULL, the default numerical decoder is used. */
433         SignalEncoder encoder; /*!< encoder        - An optional function to encode a signal value to be written to
434                                                 *       CAN into a byte array. If NULL, the default numerical encoder
435                                                 *       is used. */
436         bool received; /*!< received    - True if this signal has ever been received.*/
437         float lastValue; /*!< lastValue   - The last received value of the signal. If 'received' is false,
438                                         *       this value is undefined. */
439 };
440 typedef struct CanSignal CanSignal;
441
442 /**
443  * @brief The definition of a CAN message. This includes a lot of metadata, so
444  * to save memory this struct should not be used for storing incoming and
445  * outgoing CAN messages.
446  *
447  * @param[in] bus - A pointer to the bus this message is on.
448  * @param[in] id - The ID of the message.
449  * @param[in] format - the format of the message's ID.
450  * @param[in] clock - an optional frequency clock to control the output of this
451  *              message, if sent raw, or simply to mark the max frequency for custom
452  *              handlers to retriec++ if ? syntaxve.
453  * @param[in] forceSendChanged - If true, regardless of the frequency, it will send CAN
454  *              message if it has changed when using raw passthrough.
455  * @param[in] lastValue - The last received value of the message. Defaults to undefined.
456  *              This is required for the forceSendChanged functionality, as the stack
457  *              needs to compare an incoming CAN message with the previous frame.
458  */
459 struct CanMessageDefinition {
460         struct CanBus* bus;
461         uint32_t id;
462         CanMessageFormat format;
463         FrequencyClock frequencyClock;
464         bool forceSendChanged;
465         uint8_t lastValue[CAN_MESSAGE_SIZE];
466 };
467 typedef struct CanMessageDefinition CanMessageDefinition;
468
469 /**
470  * @brief A parent wrapper for a particular set of CAN messages and associated
471  *      CAN buses(e.g. a vehicle or program).
472  *
473  *      @param[in] index - A numerical ID for the message set, ideally the index in an array
474  *              for fast lookup
475  *      @param[in] name - The name of the message set.
476  *      @param[in] busCount - The number of CAN buses defined for this message set.
477  *      @param[in] messageCount - The number of CAN messages (across all buses) defined for
478  *              this message set.
479  *      @param[in] signalCount - The number of CAN signals (across all messages) defined for
480  *              this message set.
481  *      @param[in] commandCount - The number of CanCommmands defined for this message set.
482  */
483  typedef struct {
484         uint8_t index;
485         const char* name;
486         uint8_t busCount;
487         unsigned short messageCount;
488         unsigned short signalCount;
489         unsigned short commandCount;
490 } CanMessageSet;
491
492 /**
493  * @brief The type signature for a function to handle a custom OpenXC command.
494  *
495  * @param[in] char* name - the name of the received command.
496  * @param[in] openxc_DynamicField* value - the value of the received command, in a DynamicField. The actual type
497  *              may be a number, string or bool.
498  * @param[in] openxc_DynamicField* event - an optional event from the received command, in a DynamicField. The
499  *              actual type may be a number, string or bool.
500  * @param[in] CanSignal* signals - The list of all signals.
501  * @param[in] int signalCount - The length of the signals array.
502  */
503 typedef void (*CommandHandler)(const char* name, openxc_DynamicField* value,
504                 openxc_DynamicField* event, CanSignal* signals, int signalCount);
505
506 /* Public: The structure to represent a supported custom OpenXC command.
507  *
508  * For completely customized CAN commands without a 1-1 mapping between an
509  * OpenXC message from the host and a CAN signal, you can define the name of the
510  * command and a custom function to handle it in the VI. An example is
511  * the "turn_signal_status" command in OpenXC, which has a value of "left" or
512  * "right". The vehicle may have separate CAN signals for the left and right
513  * turn signals, so you will need to implement a custom command handler to send
514  * the correct signals.
515  *
516  * Command handlers are also useful if you want to trigger multiple CAN messages
517  * or signals from a signal OpenXC message.
518  *
519  * genericName - The name of the command.
520  * handler - An function to process the received command's data and perform some
521  *              action.
522  */
523 typedef struct {
524         const char* genericName;
525         CommandHandler handler;
526 } CanCommand;
527
528 /**
529  * @brief Pre initialize actions made before CAN bus initialization
530  *
531  * @param[in] can_bus_dev_t bus - A CanBus struct defining the bus's metadata
532  * @param[in] bool writable - configure the controller in a writable mode. If false, it will be
533  *              configured as "listen only" and will not allow writes or even CAN ACKs.
534  * @param[in] buses - An array of all CAN buses.
535  * @param[in] int busCount - The length of the buses array.
536  */
537 void pre_initialize(can_bus_dev_t* bus, bool writable, can_bus_dev_t* buses, const int busCount);
538
539 /* Post-initialize actions made after CAN bus initialization and before the
540  * event loop connection.
541  *
542  * bus - A CanBus struct defining the bus's metadata
543  * writable - configure the controller in a writable mode. If false, it will be
544  *              configured as "listen only" and will not allow writes or even CAN ACKs.
545  * buses - An array of all CAN buses.
546  * busCount - The length of the buses array.
547  */
548 void post_initialize(can_bus_dev_t* bus, bool writable, can_bus_dev_t* buses, const int busCount);
549
550 /* Public: Check if the device is connected to an active CAN bus, i.e. it's
551  * received a message in the recent past.
552  *
553  * Returns true if a message was received on the CAN bus within
554  * CAN_ACTIVE_TIMEOUT_S seconds.
555  */
556 bool isBusActive(can_bus_dev_t* bus);
557
558 /* Public: Log transfer statistics about all active CAN buses to the debug log.
559  *
560  * buses - an array of active CAN buses.
561  * busCount - the length of the buses array.
562  */
563 void logBusStatistics(can_bus_dev_t* buses, const int busCount);
564
565 /**
566  * @fn void can_reader(can_bus_dev_t& can_bus_dev, can_bus_t& can_bus);
567  *
568  * @brief Thread function used to read the can socket.
569  *
570  * @param[in] can_bus_dev_t object to be used to read the can socket
571  * @param[in] can_bus_t object used to fill can_message_q_ queue
572  */
573 void can_reader(can_bus_dev_t& can_bus_dev, can_bus_t& can_bus);
574
575 /**
576  * @fn void can_decode_message(can_bus_t& can_bus);
577  *
578  * @brief Thread function used to decode can messages read into the can_message_q_
579  *
580  * @param[in] can_bus_t object used to pop can_message_q_ queue and fill decoded message
581  * into vehicle_message_q_ queue.
582  */
583 void can_decode_message(can_bus_t& can_bus);
584
585 /**
586  * @fn void can_decode_message(can_bus_t& can_bus);
587  *
588  * @brief Thread function used to push afb_event
589  *
590  * @param[in] can_bus_t object used to pop can_message_q_ queue and fill decoded message
591  * into vehicle_message_q_ queue.
592  */
593 void can_event_push(can_bus_t& can_bus);