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