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