CPP conversion began
[apps/low-level-can-service.git] / can-utils.h
1
2 /*
3  * Copyright (C) 2015, 2016 "IoT.bzh"
4  * Author "Romain Forlot" <romain.forlot@iot.bzh>
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *   http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18
19 #pragma once
20
21 #include <string>
22 #include "timer.h"
23 #include "openxc.pb.h"
24
25 // TODO actual max is 32 but dropped to 24 for memory considerations
26 #define MAX_ACCEPTANCE_FILTERS 24
27 // TODO this takes up a ton of memory
28 #define MAX_DYNAMIC_MESSAGE_COUNT 12
29
30 #define CAN_MESSAGE_SIZE 8
31
32 #define CAN_ACTIVE_TIMEOUT_S 30
33
34 #define QUEUE_DECLARE(type, max_length) \
35 static const int queue_##type##_max_length = max_length; \
36 static const int queue_##type##_max_internal_length = max_length + 1; \
37 typedef struct queue_##type##_s { \
38     int head; \
39     int tail; \
40     type elements[max_length + 1]; \
41 } queue_##type; \
42 \
43 bool queue_##type##_push(queue_##type* queue, type value); \
44 \
45 type queue_##type##_pop(queue_##type* queue); \
46 \
47 type queue_##type##_peek(queue_##type* queue); \
48 void queue_##type##_init(queue_##type* queue); \
49 int queue_##type##_length(queue_##type* queue); \
50 int queue_##type##_available(queue_##type* queue); \
51 bool queue_##type##_full(queue_##type* queue); \
52 bool queue_##type##_empty(queue_##type* queue); \
53 void queue_##type##_snapshot(queue_##type* queue, type* snapshot, int max);
54
55 /* Public: The type signature for a CAN signal decoder.
56  *
57  * A SignalDecoder transforms a raw floating point CAN signal into a number,
58  * string or boolean.
59  *
60  * signal - The CAN signal that we are decoding.
61  * signals - The list of all signals.
62  * signalCount - The length of the signals array.
63  * pipeline -  you may want to generate arbitrary additional messages for
64  *      publishing.
65  * value - The CAN signal parsed from the message as a raw floating point
66  *      value.
67  * send - An output parameter. If the decoding failed or the CAN signal should
68  *      not send for some other reason, this should be flipped to false.
69  *
70  * Returns a decoded value in an openxc_DynamicField struct.
71  */
72 typedef openxc_DynamicField (*SignalDecoder)(struct CanSignal* signal,
73         CanSignal* signals, int signalCount,
74         openxc::pipeline::Pipeline* pipeline, float value, bool* send);
75
76 /* Public: The type signature for a CAN signal encoder.
77  *
78  * A SignalEncoder transforms a number, string or boolean into a raw floating
79  * point value that fits in the CAN signal.
80  *
81  * signal - The CAN signal to encode.
82  * value - The dynamic field to encode.
83  * send - An output parameter. If the encoding failed or the CAN signal should
84  * not be encoded for some other reason, this will be flipped to false.
85  */
86 typedef uint64_t (*SignalEncoder)(struct CanSignal* signal,
87         openxc_DynamicField* value, bool* send);
88
89 /* CanBus represent a can device definition get from configuraiton file */
90 class CanBus {
91         private:
92                 /* Got from conf file */
93                 std::string deviceName;
94
95                 int socket;
96                 bool is_fdmode_on;
97                 struct sockaddr_can txAddress;
98
99         public:
100                 int open();
101                 int close();
102 };
103
104 /* Public: The ID format for a CAN message.
105  *
106  * STANDARD - standard 11-bit CAN arbitration ID.
107  * EXTENDED - an extended frame, with a 29-bit arbitration ID.
108  */
109 enum CanMessageFormat {
110     STANDARD,
111     EXTENDED,
112 };
113 typedef enum CanMessageFormat CanMessageFormat;
114
115 /* Public: A state encoded (SED) signal's mapping from numerical values to
116  * OpenXC state names.
117  *
118  * value - The integer value of the state on the CAN bus.
119  * name  - The corresponding string name for the state in OpenXC.
120  */
121 struct CanSignalState {
122     const int value;
123     const char* name;
124 };
125 typedef struct CanSignalState CanSignalState;
126
127 /* Public: A CAN signal to decode from the bus and output over USB.
128  *
129  * message     - The message this signal is a part of.
130  * genericName - The name of the signal to be output over USB.
131  * bitPosition - The starting bit of the signal in its CAN message (assuming
132  *               non-inverted bit numbering, i.e. the most significant bit of
133  *               each byte is 0)
134  * bitSize     - The width of the bit field in the CAN message.
135  * factor      - The final value will be multiplied by this factor. Use 1 if you
136  *               don't need a factor.
137  * offset      - The final value will be added to this offset. Use 0 if you
138  *               don't need an offset.
139  * minValue    - The minimum value for the processed signal.
140  * maxValue    - The maximum value for the processed signal.
141  * frequencyClock - A FrequencyClock struct to control the maximum frequency to
142  *              process and send this signal. To process every value, set the
143  *              clock's frequency to 0.
144  * sendSame    - If true, will re-send even if the value hasn't changed.
145  * forceSendChanged - If true, regardless of the frequency, it will send the
146  *              value if it has changed.
147  * states      - An array of CanSignalState describing the mapping
148  *               between numerical and string values for valid states.
149  * stateCount  - The length of the states array.
150  * writable    - True if the signal is allowed to be written from the USB host
151  *               back to CAN. Defaults to false.
152  * decoder     - An optional function to decode a signal from the bus to a human
153  *      readable value. If NULL, the default numerical decoder is used.
154  * encoder     - An optional function to encode a signal value to be written to
155  *                CAN into a byte array. If NULL, the default numerical encoder
156  *                is used.
157  * received    - True if this signal has ever been received.
158  * lastValue   - The last received value of the signal. If 'received' is false,
159  *      this value is undefined.
160  */
161 struct CanSignal {
162     struct CanMessageDefinition* message;
163     const char* genericName;
164     uint8_t bitPosition;
165     uint8_t bitSize;
166     float factor;
167     float offset;
168     float minValue;
169     float maxValue;
170     FrequencyClock frequencyClock;
171     bool sendSame;
172     bool forceSendChanged;
173     const CanSignalState* states;
174     uint8_t stateCount;
175     bool writable;
176     SignalDecoder decoder;
177     SignalEncoder encoder;
178     bool received;
179     float lastValue;
180 };
181 typedef struct CanSignal CanSignal;
182
183 /* Public: The definition of a CAN message. This includes a lot of metadata, so
184  * to save memory this struct should not be used for storing incoming and
185  * outgoing CAN messages.
186  *
187  * bus - A pointer to the bus this message is on.
188  * id - The ID of the message.
189  * format - the format of the message's ID.
190  * frequencyClock - an optional frequency clock to control the output of this
191  *      message, if sent raw, or simply to mark the max frequency for custom
192  *      handlers to retrieve.
193  * forceSendChanged - If true, regardless of the frequency, it will send CAN
194  *      message if it has changed when using raw passthrough.
195  * lastValue - The last received value of the message. Defaults to undefined.
196  *      This is required for the forceSendChanged functionality, as the stack
197  *      needs to compare an incoming CAN message with the previous frame.
198  */
199 struct CanMessageDefinition {
200     struct CanBus* bus;
201     uint32_t id;
202     CanMessageFormat format;
203     FrequencyClock frequencyClock;
204     bool forceSendChanged;
205     uint8_t lastValue[CAN_MESSAGE_SIZE];
206 };
207 typedef struct CanMessageDefinition CanMessageDefinition;
208
209 /* A compact representation of a single CAN message, meant to be used in in/out
210  * buffers.
211  *
212  * id - The ID of the message.
213  * format - the format of the message's ID.
214  * data  - The message's data field.
215  * length - the length of the data array (max 8).
216  */
217 struct CanMessage {
218     uint32_t id;
219     CanMessageFormat format;
220     uint8_t data[CAN_MESSAGE_SIZE];
221     uint8_t length;
222 };
223 typedef struct CanMessage CanMessage;
224
225 QUEUE_DECLARE(CanMessage, 8);
226
227 /* Private: An entry in the list of acceptance filters for each CanBus.
228  *
229  * This struct is meant to be used with a LIST type from <sys/queue.h>.
230  *
231  * filter - the value for the CAN acceptance filter.
232  * activeUserCount - The number of active consumers of this filter's messages.
233  *      When 0, this filter can be removed.
234  * format - the format of the ID for the filter.
235 struct AcceptanceFilterListEntry {
236     uint32_t filter;
237     uint8_t activeUserCount;
238     CanMessageFormat format;
239     LIST_ENTRY(AcceptanceFilterListEntry) entries;
240 };
241  */
242
243 /* Private: A type of list containing CAN acceptance filters.
244 LIST_HEAD(AcceptanceFilterList, AcceptanceFilterListEntry);
245
246 struct CanMessageDefinitionListEntry {
247     CanMessageDefinition definition;
248     LIST_ENTRY(CanMessageDefinitionListEntry) entries;
249 };
250 LIST_HEAD(CanMessageDefinitionList, CanMessageDefinitionListEntry);
251  */
252
253 /** Public: A parent wrapper for a particular set of CAN messages and associated
254  *  CAN buses(e.g. a vehicle or program).
255  *
256  *  index - A numerical ID for the message set, ideally the index in an array
257  *      for fast lookup
258  *  name - The name of the message set.
259  *  busCount - The number of CAN buses defined for this message set.
260  *  messageCount - The number of CAN messages (across all buses) defined for
261  *      this message set.
262  *  signalCount - The number of CAN signals (across all messages) defined for
263  *      this message set.
264  *  commandCount - The number of CanCommmands defined for this message set.
265  */
266 typedef struct {
267     uint8_t index;
268     const char* name;
269     uint8_t busCount;
270     unsigned short messageCount;
271     unsigned short signalCount;
272     unsigned short commandCount;
273 } CanMessageSet;
274
275 /* Public: The type signature for a function to handle a custom OpenXC command.
276  *
277  * name - the name of the received command.
278  * value - the value of the received command, in a DynamicField. The actual type
279  *      may be a number, string or bool.
280  * event - an optional event from the received command, in a DynamicField. The
281  *      actual type may be a number, string or bool.
282  * signals - The list of all signals.
283  * signalCount - The length of the signals array.
284  */
285 typedef void (*CommandHandler)(const char* name, openxc_DynamicField* value,
286         openxc_DynamicField* event, CanSignal* signals, int signalCount);
287
288 /* Public: The structure to represent a supported custom OpenXC command.
289  *
290  * For completely customized CAN commands without a 1-1 mapping between an
291  * OpenXC message from the host and a CAN signal, you can define the name of the
292  * command and a custom function to handle it in the VI. An example is
293  * the "turn_signal_status" command in OpenXC, which has a value of "left" or
294  * "right". The vehicle may have separate CAN signals for the left and right
295  * turn signals, so you will need to implement a custom command handler to send
296  * the correct signals.
297  *
298  * Command handlers are also useful if you want to trigger multiple CAN messages
299  * or signals from a signal OpenXC message.
300  *
301  * genericName - The name of the command.
302  * handler - An function to process the received command's data and perform some
303  *      action.
304  */
305 typedef struct {
306     const char* genericName;
307     CommandHandler handler;
308 } CanCommand;
309
310 /* Pre initialize actions made before CAN bus initialization
311  *
312  * bus - A CanBus struct defining the bus's metadata
313  * writable - configure the controller in a writable mode. If false, it will be
314  *      configured as "listen only" and will not allow writes or even CAN ACKs.
315  * buses - An array of all CAN buses.
316  * busCount - The length of the buses array.
317  */
318 void pre_initialize(CanBus* bus, bool writable, CanBus* buses, const int busCount);
319
320 /* Post-initialize actions made after CAN bus initialization and before the
321  * event loop connection.
322  *
323  * bus - A CanBus struct defining the bus's metadata
324  * writable - configure the controller in a writable mode. If false, it will be
325  *      configured as "listen only" and will not allow writes or even CAN ACKs.
326  * buses - An array of all CAN buses.
327  * busCount - The length of the buses array.
328  */
329 void post_initialize(CanBus* bus, bool writable, CanBus* buses, const int busCount);
330
331 /* Public: Check if the device is connected to an active CAN bus, i.e. it's
332  * received a message in the recent past.
333  *
334  * Returns true if a message was received on the CAN bus within
335  * CAN_ACTIVE_TIMEOUT_S seconds.
336  */
337 bool isBusActive(CanBus* bus);
338
339 /* Public: Log transfer statistics about all active CAN buses to the debug log.
340  *
341  * buses - an array of active CAN buses.
342  * busCount - the length of the buses array.
343  */
344 void logBusStatistics(CanBus* buses, const int busCount);