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