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