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