Change way to convert simplemessage into a json
[apps/agl-service-can-low-level.git] / src / can-utils.hpp
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 <map>
21 #include <queue>
22 #include <vector>
23 #include <cstdio>
24 #include <string>
25 #include <thread>
26 #include <fcntl.h>
27 #include <unistd.h>
28 #include <net/if.h>
29 #include <sys/ioctl.h>
30 #include <linux/can.h>
31 #include <sys/socket.h>
32 #include <json-c/json.h>
33 #include <linux/can/raw.h>
34
35 #include "timer.hpp"
36 #include "openxc.pb.h"
37
38 extern "C"
39 {
40         #include <afb/afb-binding.h>
41         #include <afb/afb-service-itf.h>
42 }
43
44 // TODO actual max is 32 but dropped to 24 for memory considerations
45 #define MAX_ACCEPTANCE_FILTERS 24
46 // TODO this takes up a ton of memory
47 #define MAX_DYNAMIC_MESSAGE_COUNT 12
48
49 #define CAN_MESSAGE_SIZE 8
50
51 #define CAN_ACTIVE_TIMEOUT_S 30
52
53 /**
54  * @brief The type signature for a CAN signal decoder.
55  *
56  * @desc A SignalDecoder transforms a raw floating point CAN signal into a number,
57  * string or boolean.
58  *
59  * @param[in] CanSignal signal - The CAN signal that we are decoding.
60  * @param[in] CanSignal signals - The list of all signals.
61  * @param[in] int signalCount - The length of the signals array.
62  * @param[in] float value - The CAN signal parsed from the message as a raw floating point
63  *      value.
64  * @param[out] bool 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  * @return 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 /**
73  * @brief: The type signature for a CAN signal encoder.
74  *
75  * @desc A SignalEncoder transforms a number, string or boolean into a raw floating
76  * point value that fits in the CAN signal.
77  *
78  * @params[signal] - The CAN signal to encode. 
79  * @params[value] - The dynamic field to encode.
80  * @params[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 /**
87  * @brief The ID format for a CAN message.
88  *
89  * STANDARD - standard 11-bit CAN arbitration ID.
90  * EXTENDED - an extended frame, with a 29-bit arbitration ID.
91  */
92 enum CanMessageFormat {
93         STANDARD,
94         EXTENDED,
95 };
96 typedef enum CanMessageFormat CanMessageFormat;
97
98 /**
99  * @brief A compact representation of a single CAN message, meant to be used in in/out
100  * buffers.
101  *
102  * param[in] uint32_t id - The ID of the message.
103  * param[in] CanMessageFormat format - the format of the message's ID.
104  * param[in] uint8_t data  - The message's data field.
105  * @param[in] uint8_t length - the length of the data array (max 8).
106 *************************
107 * old CanMessage struct *
108 *************************
109 struct CanMessage {
110         uint32_t id;
111         CanMessageFormat format;
112         uint8_t data[CAN_MESSAGE_SIZE];
113         uint8_t length;
114 };
115 typedef struct CanMessage CanMessage;
116 */
117 class can_message_t {
118         private:
119                 const struct afb_binding_interface* interface_;
120                 uint32_t id_;
121                 CanMessageFormat format_;
122                 uint8_t data_;
123                 uint8_t length_;
124
125         public:
126                 can_message_t(const struct afb_binding_interface* interface);
127
128                 uint32_t get_id() const;
129                 int get_format() const;
130                 const uint8_t* get_data() const;
131                 uint8_t get_length() const;
132
133                 void set_id(const uint32_t new_id);
134                 void set_format(const CanMessageFormat format);
135                 void set_data(const uint8_t new_data);
136                 void set_length(const uint8_t new_length);
137
138                 void convert_from_canfd_frame(const canfd_frame& frame);
139                 canfd_frame convert_to_canfd_frame();
140 };
141
142 /** 
143  * @brief Object used to handle decoding and manage event queue to be pushed.
144  *
145  * @params[in] interface_ - afb_binding_interface pointer to the binder. Used to log messages
146  * @params[in] conf_file_ - configuration file handle used to initialize can_bus_dev_t objects.
147  */
148 class can_bus_t {
149         private:
150                 int conf_file_;
151                 
152                 std::thread th_decoding_;
153                 std::thread th_pushing_;
154
155                 bool has_can_message_;
156                 std::queue <can_message_t> can_message_q_;
157
158                 bool has_vehicle_message_;
159                 std::queue <openxc_VehicleMessage> vehicle_message_q_;
160
161         public:
162                 const struct afb_binding_interface *interface_;
163
164                 can_bus_t(const struct afb_binding_interface *itf, int& conf_file);
165                 int init_can_dev();
166                 std::vector<std::string> read_conf();
167                 
168                 void start_threads();
169
170                 can_message_t next_can_message();
171                 void push_new_can_message(const can_message_t& can_msg);                
172                 bool has_can_message() const;
173                 
174                 openxc_VehicleMessage next_vehicle_message();
175                 void push_new_vehicle_message(const openxc_VehicleMessage& v_msg);
176                 bool has_vehicle_message() const;
177 };
178
179 /** 
180  * @brief Object representing a can device. Handle opening, closing and reading on the
181  * socket. This is the low level object to be use by can_bus_t.
182  *
183  * @params[in] std::string device_name_ - name of the linux device handling the can bus. Generally vcan0, can0, etc.
184  */
185 class can_bus_dev_t {
186         private:
187                 std::string device_name_;
188                 int can_socket_;
189                 bool is_fdmode_on_;
190                 struct sockaddr_can txAddress_;
191
192                 std::thread th_reading_;
193                 bool is_running_;
194
195         public:
196                 can_bus_dev_t(const std::string& dev_name);
197
198                 int open(const struct afb_binding_interface* interface);
199                 int close();
200                 bool is_running();
201                 void start_reading(can_bus_t& can_bus);
202                 canfd_frame read(const struct afb_binding_interface *interface);
203                 
204                 int send_can_message(can_message_t& can_msg, const struct afb_binding_interface* interface);
205 };
206
207 /**
208  * @brief A state encoded (SED) signal's mapping from numerical values to
209  * OpenXC state names.
210  *
211  * @param[in] in value - The integer value of the state on the CAN bus.
212  * @param[in] char* name  - The corresponding string name for the state in OpenXC.
213  */
214 struct CanSignalState {
215         const int value;
216         const char* name;
217 };
218 typedef struct CanSignalState CanSignalState;
219
220 /**
221  * @brief A CAN signal to decode from the bus and output over USB.
222  *
223  * @param[in] message      - The message this signal is a part of.
224  * @param[in] genericName - The name of the signal to be output over USB.
225  * @param[in] bitPosition - The starting bit of the signal in its CAN message (assuming
226  *                               non-inverted bit numbering, i.e. the most significant bit of
227  *                               each byte is 0)
228  * @param[in] bitSize      - The width of the bit field in the CAN message.
229  * @param[in] factor       - The final value will be multiplied by this factor. Use 1 if you
230  *                               don't need a factor.
231  * @param[in] offset       - The final value will be added to this offset. Use 0 if you
232  *                               don't need an offset.
233  * @param[in] minValue    - The minimum value for the processed signal.
234  * @param[in] maxValue    - The maximum value for the processed signal.
235  * @param[in] frequencyClock - A FrequencyClock struct to control the maximum frequency to
236  *                              process and send this signal. To process every value, set the
237  *                              clock's frequency to 0.
238  * @param[in] sendSame    - If true, will re-send even if the value hasn't changed.
239  * @param[in] forceSendChanged - If true, regardless of the frequency, it will send the
240  *                              value if it has changed.
241  * @param[in] states       - An array of CanSignalState describing the mapping
242  *                               between numerical and string values for valid states.
243  * @param[in] stateCount  - The length of the states array.
244  * @param[in] writable    - True if the signal is allowed to be written from the USB host
245  *                               back to CAN. Defaults to false.
246  * @param[in] decoder      - An optional function to decode a signal from the bus to a human
247  *                              readable value. If NULL, the default numerical decoder is used.
248  * @param[in] encoder      - An optional function to encode a signal value to be written to
249  *                                CAN into a byte array. If NULL, the default numerical encoder
250  *                                is used.
251  * @param[in] received    - True if this signal has ever been received.
252  * @param[in] lastValue   - The last received value of the signal. If 'received' is false,
253  *              this value is undefined.
254  */
255 struct CanSignal {
256         struct CanMessageDefinition* message;
257         const char* genericName;
258         uint8_t bitPosition;
259         uint8_t bitSize;
260         float factor;
261         float offset;
262         float minValue;
263         float maxValue;
264         FrequencyClock frequencyClock;
265         bool sendSame;
266         bool forceSendChanged;
267         const CanSignalState* states;
268         uint8_t stateCount;
269         bool writable;
270         SignalDecoder decoder;
271         SignalEncoder encoder;
272         bool received;
273         float lastValue;
274 };
275 typedef struct CanSignal CanSignal;
276
277 /**
278  * @brief The definition of a CAN message. This includes a lot of metadata, so
279  * to save memory this struct should not be used for storing incoming and
280  * outgoing CAN messages.
281  *
282  * @param[in] bus - A pointer to the bus this message is on.
283  * @param[in] id - The ID of the message.
284  * @param[in] format - the format of the message's ID.
285  * @param[in] clock - an optional frequency clock to control the output of this
286  *              message, if sent raw, or simply to mark the max frequency for custom
287  *              handlers to retriec++ if ? syntaxve.
288  * @param[in] forceSendChanged - If true, regardless of the frequency, it will send CAN
289  *              message if it has changed when using raw passthrough.
290  * @param[in] lastValue - The last received value of the message. Defaults to undefined.
291  *              This is required for the forceSendChanged functionality, as the stack
292  *              needs to compare an incoming CAN message with the previous frame.
293  */
294 struct CanMessageDefinition {
295         struct CanBus* bus;
296         uint32_t id;
297         CanMessageFormat format;
298         FrequencyClock frequencyClock;
299         bool forceSendChanged;
300         uint8_t lastValue[CAN_MESSAGE_SIZE];
301 };
302 typedef struct CanMessageDefinition CanMessageDefinition;
303
304 /**
305  * @brief A parent wrapper for a particular set of CAN messages and associated
306  *      CAN buses(e.g. a vehicle or program).
307  *
308  *      @param[in] index - A numerical ID for the message set, ideally the index in an array
309  *              for fast lookup
310  *      @param[in] name - The name of the message set.
311  *      @param[in] busCount - The number of CAN buses defined for this message set.
312  *      @param[in] messageCount - The number of CAN messages (across all buses) defined for
313  *              this message set.
314  *      @param[in] signalCount - The number of CAN signals (across all messages) defined for
315  *              this message set.
316  *      @param[in] commandCount - The number of CanCommmands defined for this message set.
317  */
318  typedef struct {
319         uint8_t index;
320         const char* name;
321         uint8_t busCount;
322         unsigned short messageCount;
323         unsigned short signalCount;
324         unsigned short commandCount;
325 } CanMessageSet;
326
327 /**
328  * @brief The type signature for a function to handle a custom OpenXC command.
329  *
330  * @param[in] char* name - the name of the received command.
331  * @param[in] openxc_DynamicField* value - the value of the received command, in a DynamicField. The actual type
332  *              may be a number, string or bool.
333  * @param[in] openxc_DynamicField* event - an optional event from the received command, in a DynamicField. The
334  *              actual type may be a number, string or bool.
335  * @param[in] CanSignal* signals - The list of all signals.
336  * @param[in] int signalCount - The length of the signals array.
337  */
338 typedef void (*CommandHandler)(const char* name, openxc_DynamicField* value,
339                 openxc_DynamicField* event, CanSignal* signals, int signalCount);
340
341 /* Public: The structure to represent a supported custom OpenXC command.
342  *
343  * For completely customized CAN commands without a 1-1 mapping between an
344  * OpenXC message from the host and a CAN signal, you can define the name of the
345  * command and a custom function to handle it in the VI. An example is
346  * the "turn_signal_status" command in OpenXC, which has a value of "left" or
347  * "right". The vehicle may have separate CAN signals for the left and right
348  * turn signals, so you will need to implement a custom command handler to send
349  * the correct signals.
350  *
351  * Command handlers are also useful if you want to trigger multiple CAN messages
352  * or signals from a signal OpenXC message.
353  *
354  * genericName - The name of the command.
355  * handler - An function to process the received command's data and perform some
356  *              action.
357  */
358 typedef struct {
359         const char* genericName;
360         CommandHandler handler;
361 } CanCommand;
362
363 /**
364  * @brief Pre initialize actions made before CAN bus initialization
365  *
366  * @param[in] can_bus_dev_t bus - A CanBus struct defining the bus's metadata
367  * @param[in] bool writable - configure the controller in a writable mode. If false, it will be
368  *              configured as "listen only" and will not allow writes or even CAN ACKs.
369  * @param[in] buses - An array of all CAN buses.
370  * @param[in] int busCount - The length of the buses array.
371  */
372 void pre_initialize(can_bus_dev_t* bus, bool writable, can_bus_dev_t* buses, const int busCount);
373
374 /* Post-initialize actions made after CAN bus initialization and before the
375  * event loop connection.
376  *
377  * bus - A CanBus struct defining the bus's metadata
378  * writable - configure the controller in a writable mode. If false, it will be
379  *              configured as "listen only" and will not allow writes or even CAN ACKs.
380  * buses - An array of all CAN buses.
381  * busCount - The length of the buses array.
382  */
383 void post_initialize(can_bus_dev_t* bus, bool writable, can_bus_dev_t* buses, const int busCount);
384
385 /* Public: Check if the device is connected to an active CAN bus, i.e. it's
386  * received a message in the recent past.
387  *
388  * Returns true if a message was received on the CAN bus within
389  * CAN_ACTIVE_TIMEOUT_S seconds.
390  */
391 bool isBusActive(can_bus_dev_t* bus);
392
393 /* Public: Log transfer statistics about all active CAN buses to the debug log.
394  *
395  * buses - an array of active CAN buses.
396  * busCount - the length of the buses array.
397  */
398 void logBusStatistics(can_bus_dev_t* buses, const int busCount);
399
400 /**
401  * @brief Function representing thread activated by can bus objects
402  */
403 void can_reader(can_bus_dev_t& can_bus_dev, can_bus_t& can_bus);
404 void can_decode_message(can_bus_t& can_bus);
405 void can_event_push(can_bus_t& can_bus);