7d00dd1ac1d72555d15ed43de99f1b20e326b1db
[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 "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  * pipeline -  you may want to generate arbitrary additional messages for
63  *      publishing.
64  * value - The CAN signal parsed from the message as a raw floating point
65  *      value.
66  * send - An output parameter. If the decoding failed or the CAN signal should
67  *      not send for some other reason, this should be flipped to false.
68  *
69  * Returns a decoded value in an openxc_DynamicField struct.
70  */
71 typedef openxc_DynamicField (*SignalDecoder)(struct CanSignal* signal,
72         CanSignal* signals, int signalCount,
73         openxc::pipeline::Pipeline* pipeline, float value, bool* send);
74
75 /* Public: The type signature for a CAN signal encoder.
76  *
77  * A SignalEncoder transforms a number, string or boolean into a raw floating
78  * point value that fits in the CAN signal.
79  *
80  * signal - The CAN signal to encode.
81  * value - The dynamic field to encode.
82  * send - An output parameter. If the encoding failed or the CAN signal should
83  * not be encoded for some other reason, this will be flipped to false.
84  */
85 typedef uint64_t (*SignalEncoder)(struct CanSignal* signal,
86         openxc_DynamicField* value, bool* send);
87
88 /* Public: The ID format for a CAN message.
89  *
90  * STANDARD - standard 11-bit CAN arbitration ID.
91  * EXTENDED - an extended frame, with a 29-bit arbitration ID.
92  */
93 enum CanMessageFormat {
94     STANDARD,
95     EXTENDED,
96 };
97 typedef enum CanMessageFormat CanMessageFormat;
98
99 /* Public: A state encoded (SED) signal's mapping from numerical values to
100  * OpenXC state names.
101  *
102  * value - The integer value of the state on the CAN bus.
103  * name  - The corresponding string name for the state in OpenXC.
104  */
105 struct CanSignalState {
106     const int value;
107     const char* name;
108 };
109 typedef struct CanSignalState CanSignalState;
110
111 /* Public: A CAN signal to decode from the bus and output over USB.
112  *
113  * message     - The message this signal is a part of.
114  * genericName - The name of the signal to be output over USB.
115  * bitPosition - The starting bit of the signal in its CAN message (assuming
116  *               non-inverted bit numbering, i.e. the most significant bit of
117  *               each byte is 0)
118  * bitSize     - The width of the bit field in the CAN message.
119  * factor      - The final value will be multiplied by this factor. Use 1 if you
120  *               don't need a factor.
121  * offset      - The final value will be added to this offset. Use 0 if you
122  *               don't need an offset.
123  * minValue    - The minimum value for the processed signal.
124  * maxValue    - The maximum value for the processed signal.
125  * frequencyClock - A FrequencyClock struct to control the maximum frequency to
126  *              process and send this signal. To process every value, set the
127  *              clock's frequency to 0.
128  * sendSame    - If true, will re-send even if the value hasn't changed.
129  * forceSendChanged - If true, regardless of the frequency, it will send the
130  *              value if it has changed.
131  * states      - An array of CanSignalState describing the mapping
132  *               between numerical and string values for valid states.
133  * stateCount  - The length of the states array.
134  * writable    - True if the signal is allowed to be written from the USB host
135  *               back to CAN. Defaults to false.
136  * decoder     - An optional function to decode a signal from the bus to a human
137  *      readable value. If NULL, the default numerical decoder is used.
138  * encoder     - An optional function to encode a signal value to be written to
139  *                CAN into a byte array. If NULL, the default numerical encoder
140  *                is used.
141  * received    - True if this signal has ever been received.
142  * lastValue   - The last received value of the signal. If 'received' is false,
143  *      this value is undefined.
144  */
145 struct CanSignal {
146     struct CanMessageDefinition* message;
147     const char* genericName;
148     uint8_t bitPosition;
149     uint8_t bitSize;
150     float factor;
151     float offset;
152     float minValue;
153     float maxValue;
154     FrequencyClock frequencyClock;
155     bool sendSame;
156     bool forceSendChanged;
157     const CanSignalState* states;
158     uint8_t stateCount;
159     bool writable;
160     SignalDecoder decoder;
161     SignalEncoder encoder;
162     bool received;
163     float lastValue;
164 };
165 typedef struct CanSignal CanSignal;
166
167 /* Public: The definition of a CAN message. This includes a lot of metadata, so
168  * to save memory this struct should not be used for storing incoming and
169  * outgoing CAN messages.
170  *
171  * bus - A pointer to the bus this message is on.
172  * id - The ID of the message.
173  * format - the format of the message's ID.
174  * frequencyClock - an optional frequency clock to control the output of this
175  *      message, if sent raw, or simply to mark the max frequency for custom
176  *      handlers to retrieve.
177  * forceSendChanged - If true, regardless of the frequency, it will send CAN
178  *      message if it has changed when using raw passthrough.
179  * lastValue - The last received value of the message. Defaults to undefined.
180  *      This is required for the forceSendChanged functionality, as the stack
181  *      needs to compare an incoming CAN message with the previous frame.
182  */
183 struct CanMessageDefinition {
184     struct CanBus* bus;
185     uint32_t id;
186     CanMessageFormat format;
187     FrequencyClock frequencyClock;
188     bool forceSendChanged;
189     uint8_t lastValue[CAN_MESSAGE_SIZE];
190 };
191 typedef struct CanMessageDefinition CanMessageDefinition;
192
193 /* A compact representation of a single CAN message, meant to be used in in/out
194  * buffers.
195  *
196  * id - The ID of the message.
197  * format - the format of the message's ID.
198  * data  - The message's data field.
199  * length - the length of the data array (max 8).
200  */
201 struct CanMessage {
202     uint32_t id;
203     CanMessageFormat format;
204     uint8_t data[CAN_MESSAGE_SIZE];
205     uint8_t length;
206 };
207 typedef struct CanMessage CanMessage;
208
209 QUEUE_DECLARE(CanMessage, 8);
210
211 /* Private: An entry in the list of acceptance filters for each CanBus.
212  *
213  * This struct is meant to be used with a LIST type from <sys/queue.h>.
214  *
215  * filter - the value for the CAN acceptance filter.
216  * activeUserCount - The number of active consumers of this filter's messages.
217  *      When 0, this filter can be removed.
218  * format - the format of the ID for the filter.
219 struct AcceptanceFilterListEntry {
220     uint32_t filter;
221     uint8_t activeUserCount;
222     CanMessageFormat format;
223     LIST_ENTRY(AcceptanceFilterListEntry) entries;
224 };
225  */
226
227 /* Private: A type of list containing CAN acceptance filters.
228 LIST_HEAD(AcceptanceFilterList, AcceptanceFilterListEntry);
229
230 struct CanMessageDefinitionListEntry {
231     CanMessageDefinition definition;
232     LIST_ENTRY(CanMessageDefinitionListEntry) entries;
233 };
234 LIST_HEAD(CanMessageDefinitionList, CanMessageDefinitionListEntry);
235  */
236
237 /** Public: A parent wrapper for a particular set of CAN messages and associated
238  *  CAN buses(e.g. a vehicle or program).
239  *
240  *  index - A numerical ID for the message set, ideally the index in an array
241  *      for fast lookup
242  *  name - The name of the message set.
243  *  busCount - The number of CAN buses defined for this message set.
244  *  messageCount - The number of CAN messages (across all buses) defined for
245  *      this message set.
246  *  signalCount - The number of CAN signals (across all messages) defined for
247  *      this message set.
248  *  commandCount - The number of CanCommmands defined for this message set.
249  */
250 typedef struct {
251     uint8_t index;
252     const char* name;
253     uint8_t busCount;
254     unsigned short messageCount;
255     unsigned short signalCount;
256     unsigned short commandCount;
257 } CanMessageSet;
258
259 /* Public: The type signature for a function to handle a custom OpenXC command.
260  *
261  * name - the name of the received command.
262  * value - the value of the received command, in a DynamicField. The actual type
263  *      may be a number, string or bool.
264  * event - an optional event from the received command, in a DynamicField. The
265  *      actual type may be a number, string or bool.
266  * signals - The list of all signals.
267  * signalCount - The length of the signals array.
268  */
269 typedef void (*CommandHandler)(const char* name, openxc_DynamicField* value,
270         openxc_DynamicField* event, CanSignal* signals, int signalCount);
271
272 /* Public: The structure to represent a supported custom OpenXC command.
273  *
274  * For completely customized CAN commands without a 1-1 mapping between an
275  * OpenXC message from the host and a CAN signal, you can define the name of the
276  * command and a custom function to handle it in the VI. An example is
277  * the "turn_signal_status" command in OpenXC, which has a value of "left" or
278  * "right". The vehicle may have separate CAN signals for the left and right
279  * turn signals, so you will need to implement a custom command handler to send
280  * the correct signals.
281  *
282  * Command handlers are also useful if you want to trigger multiple CAN messages
283  * or signals from a signal OpenXC message.
284  *
285  * genericName - The name of the command.
286  * handler - An function to process the received command's data and perform some
287  *      action.
288  */
289 typedef struct {
290     const char* genericName;
291     CommandHandler handler;
292 } CanCommand;
293
294 /* Pre initialize actions made before CAN bus initialization
295  *
296  * bus - A CanBus struct defining the bus's metadata
297  * writable - configure the controller in a writable mode. If false, it will be
298  *      configured as "listen only" and will not allow writes or even CAN ACKs.
299  * buses - An array of all CAN buses.
300  * busCount - The length of the buses array.
301  */
302 void pre_initialize(CanBus* bus, bool writable, CanBus* buses, const int busCount);
303
304 /* Post-initialize actions made after CAN bus initialization and before the
305  * event loop connection.
306  *
307  * bus - A CanBus struct defining the bus's metadata
308  * writable - configure the controller in a writable mode. If false, it will be
309  *      configured as "listen only" and will not allow writes or even CAN ACKs.
310  * buses - An array of all CAN buses.
311  * busCount - The length of the buses array.
312  */
313 void post_initialize(CanBus* bus, bool writable, CanBus* buses, const int busCount);
314
315 /* Public: Check if the device is connected to an active CAN bus, i.e. it's
316  * received a message in the recent past.
317  *
318  * Returns true if a message was received on the CAN bus within
319  * CAN_ACTIVE_TIMEOUT_S seconds.
320  */
321 bool isBusActive(CanBus* bus);
322
323 /* Public: Log transfer statistics about all active CAN buses to the debug log.
324  *
325  * buses - an array of active CAN buses.
326  * busCount - the length of the buses array.
327  */
328 void logBusStatistics(CanBus* buses, const int busCount);