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