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