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