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