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