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