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