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