2e79148ff540fc530e457d9a4214c5a3416544ad
[apps/agl-service-can-low-level.git] / low-can-binding / can / can-encoder.cpp
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 #include "can-encoder.hpp"
19
20 #include "canutil/write.h"
21 #include "../utils/openxc-utils.hpp"
22 #include "message-definition.hpp"
23 #include "../utils/converter.hpp"
24
25 /**
26  * @brief Allows to encode data for a signal
27  *
28  * @param sig The signal to know its location
29  * @param data The data to encod
30  * @param filter If true that will generate the filter BCM for the signal
31  * @param factor If true that will use the factor of the signal else 1
32  * @param offset If true that will use the offset of the signal else 0
33  */
34 void encoder_t::encode_data(std::shared_ptr<signal_t> sig, std::vector<uint8_t> &data, bool filter, bool factor, bool offset)
35 {
36         uint32_t bit_size = sig->get_bit_size();
37         uint32_t bit_position = sig->get_bit_position();
38         float factor_v = factor ? sig->get_factor() : 1;
39         float offset_v = offset ? sig->get_offset() : 0;
40
41         int new_start_byte = 0;
42         int new_end_byte = 0;
43         uint8_t new_start_bit = 0;
44         uint8_t new_end_bit = 0;
45
46         converter_t::signal_to_bits_bytes(bit_position, bit_size, new_start_byte, new_end_byte, new_start_bit, new_end_bit);
47         std::vector<uint8_t> data_signal(new_end_byte - new_start_byte + 1);
48
49         if(filter)
50         {
51                 for (auto& elt: data_signal)
52                         elt = 0xFF;
53                 uint8_t mask_first_v = static_cast<uint8_t>(0xFF << new_start_bit);
54                 uint8_t mask_last_v = static_cast<uint8_t>(0xFF >> (7 - new_end_bit));
55
56                 if(new_start_byte == new_end_byte)
57                 {
58                         data_signal[0] = mask_first_v & mask_last_v;
59                 }
60                 else
61                 {
62                         data_signal[0] = mask_first_v;
63                         data_signal[new_end_byte - new_start_byte] = mask_last_v;
64                 }
65         }
66         else
67         {
68                 bitfield_encode_float(sig->get_last_value(),
69                                       new_start_bit,
70                                       bit_size,
71                                       factor_v,
72                                       offset_v,
73                                       data_signal.data(),
74                                       bit_size);
75         }
76
77         for(size_t i = new_start_byte; i <= new_end_byte ; i++)
78                 data[i] = data[i] | data_signal[i-new_start_byte];
79 }
80
81 /**
82  * @brief Allows to build a multi frame message with correct data to be send
83  *
84  * @param signal The CAN signal to write, including the bit position and bit size.
85  * @param value The encoded integer value to write in the CAN signal.
86  * @param message A multi frame message to complete
87  * @param factor If true that will use the factor of the signal else 1
88  * @param offset If true that will use the offset of the signal else 0
89  * @return message_t*  The message that is generated
90  */
91 message_t* encoder_t::build_frame(const std::shared_ptr<signal_t>& signal, uint64_t value, message_t *message, bool factor, bool offset)
92 {
93         signal->set_last_value(static_cast<float>(value));
94         std::vector<uint8_t> data(message->get_length(), 0);
95
96         for(const auto& sig: signal->get_message()->get_signals())
97                 encode_data(sig, data, false, factor, offset);
98
99         message->set_data(data);
100         return message;
101 }
102
103 /**
104  * @brief Allows to build a message_t with correct data to be send
105  *
106  * @param signal The CAN signal to write, including the bit position and bit size.
107  * @param value The encoded integer value to write in the CAN signal.
108  * @param factor If true that will use the factor of the signal else 1
109  * @param offset If true that will use the offset of the signal else 0
110  * @return message_t* The message that is generated
111  */
112 message_t* encoder_t::build_message(const std::shared_ptr<signal_t>& signal, uint64_t value, bool factor, bool offset)
113 {
114         message_t *message;
115         std::vector<uint8_t> data;
116         switch(signal->get_message()->get_flags())
117         {
118                 case CAN_PROTOCOL_WITH_FD_FRAME:
119                         message = new can_message_t(CANFD_MAX_DLEN,
120                                                     signal->get_message()->get_id(),
121                                                     CANFD_MAX_DLEN,
122                                                     false,
123                                                     signal->get_message()->get_flags(),
124                                                     data,
125                                                     0);
126                         return build_frame(signal, value, message, factor, offset);
127 #ifdef USE_FEATURE_J1939
128                 case J1939_PROTOCOL:
129                         message = new j1939_message_t(signal->get_message()->get_length(),
130                                                       data,
131                                                       0,
132                                                       J1939_NO_NAME,
133                                                       signal->get_message()->get_id(),
134                                                       J1939_NO_ADDR);
135                         return build_frame(signal, value, message, factor, offset);
136 #endif
137                 case CAN_PROTOCOL:
138                         message = new can_message_t(CAN_MAX_DLEN,
139                                                     signal->get_message()->get_id(),
140                                                     CAN_MAX_DLEN,
141                                                     false,
142                                                     signal->get_message()->get_flags(),
143                                                     data,
144                                                     0);
145                         return build_frame(signal, value, message, factor, offset);
146                 default:
147                         message = new can_message_t(CAN_MAX_DLEN,
148                                                     signal->get_message()->get_id(),
149                                                     CAN_MAX_DLEN,
150                                                     false,
151                                                     signal->get_message()->get_flags(),
152                                                     data,
153                                                     0);
154                         return build_frame(signal, value, message, factor, offset);
155         }
156
157 }
158
159
160 /**
161  * @brief Allows to build a single frame message with correct data to be send
162  *
163  * @param signal The CAN signal to write, including the bit position and bit size.
164  * @param value The encoded integer value to write in the CAN signal.
165  * @param message A single frame message to complete
166  * @return message_t*  The message that is generated
167  */
168 message_t* encoder_t::build_one_frame_message(const std::shared_ptr<signal_t>& signal, uint64_t value, message_t *message)
169 {
170         signal->set_last_value((float)value);
171         std::vector<uint8_t> data;
172         data.reserve(message->get_length());
173
174         for(const auto& sig: signal->get_message()->get_signals())
175         {
176                 float last_value = sig->get_last_value();
177                 bitfield_encode_float(last_value,
178                                         static_cast<uint8_t>(sig->get_bit_position()),
179                                         static_cast<uint8_t>(sig->get_bit_size()),
180                                         sig->get_factor(),
181                                         sig->get_offset(),
182                                         data.data(),
183                                         static_cast<uint8_t>(message->get_length()));
184         }
185
186         message->set_data(data);
187         return message;
188 }
189
190 /**
191  * @brief Allows to build a multi frame message with correct data to be send
192  *
193  * @param signal The CAN signal to write, including the bit position and bit size.
194  * @param value The encoded integer value to write in the CAN signal.
195  * @param message A multi frame message to complete
196  * @return message_t*  The message that is generated
197  */
198 message_t* encoder_t::build_multi_frame_message(const std::shared_ptr<signal_t>& signal, uint64_t value, message_t *message)
199 {
200         signal->set_last_value((float)value);
201         int nb_of_frame;
202         uint32_t msgs_len = signal->get_message()->get_length(); // multi frame - number of bytes
203         int max_dlen = signal->get_message()->get_flags() & CAN_PROTOCOL_WITH_FD_FRAME ? CANFD_MAX_DLEN : CAN_MAX_DLEN;
204
205         nb_of_frame = (int) msgs_len / max_dlen;
206         std::vector<uint8_t> data_tab;
207         data_tab.reserve(nb_of_frame * max_dlen);
208
209         for(const auto& sig: signal->get_message()->get_signals())
210                 // TODO: find a way to handle huge signal
211                 bitfield_encode_float(sig->get_last_value(),
212                                         sig->get_bit_position() % 64,
213                                         (uint8_t) sig->get_bit_size(),
214                                         sig->get_factor(),
215                                         sig->get_offset(),
216                                         data_tab.data() + (sig->get_bit_position() / 64),
217                                         (nb_of_frame * max_dlen) - (sig->get_bit_position() / 64));
218
219         message->set_data(data_tab);
220         return message;
221 }
222
223 /**
224  * @brief Allows to build a message_t with correct data to be send
225  *
226  * @param signal The CAN signal to write, including the bit position and bit size.
227  * @param value The encoded integer value to write in the CAN signal.
228  * @return message_t* The message that is generated
229  */
230 message_t* encoder_t::build_message(const std::shared_ptr<signal_t>& signal, uint64_t value)
231 {
232         message_t *message;
233         std::vector<uint8_t> data;
234
235         switch(signal->get_message()->get_flags())
236         {
237                 case CAN_PROTOCOL_WITH_FD_FRAME:
238                         message = new can_message_t(CANFD_MAX_DLEN,
239                                                 signal->get_message()->get_id(),
240                                                 CANFD_MAX_DLEN,
241                                                 false,
242                                                 signal->get_message()->get_flags(),
243                                                 data,
244                                                 0);
245                         return build_one_frame_message(signal, value, message);
246 #ifdef USE_FEATURE_J1939
247                 case J1939_PROTOCOL:
248                         message = new j1939_message_t(signal->get_message()->get_length(),
249                                                 data,
250                                                 0,
251                                                 J1939_NO_NAME,
252                                                 signal->get_message()->get_id(),
253                                                 J1939_NO_ADDR);
254                         return build_multi_frame_message(signal, value, message);
255 #endif
256         case CAN_PROTOCOL:
257                 message = new can_message_t(CAN_MAX_DLEN,
258                                             signal->get_message()->get_id(),
259                                             CAN_MAX_DLEN,
260                                             false,
261                                             signal->get_message()->get_flags(),
262                                             data,
263                                             0);
264                 return build_one_frame_message(signal, value, message);
265         default:
266                 message = new can_message_t(CAN_MAX_DLEN,
267                                             signal->get_message()->get_id(),
268                                             CAN_MAX_DLEN,
269                                             false,
270                                             signal->get_message()->get_flags(),
271                                             data,
272                                             0);
273                 return build_one_frame_message(signal, value, message);
274         }
275 }
276
277 /// @brief Encode a boolean into an integer, fit for a CAN signal bitfield.
278 ///
279 /// This is a shortcut for encodeDynamicField(CanSignal*, openxc_DynamicField*,
280 /// bool*) that takes care of creating the DynamicField object for you with the
281 /// boolean value.
282 ///
283 /// @param[in] signal  - The CAN signal to encode this value for..
284 /// @param[in] value - The boolean value to encode
285 /// @param[out] send - An output argument that will be set to false if the value should
286 ///     not be sent for any reason.
287 ///
288 /// @return Returns the encoded integer. If 'send' is changed to false, the field could
289 /// not be encoded and the return value is undefined.
290 ///
291 uint64_t encoder_t::encode_boolean(const signal_t& signal, bool value, bool* send)
292 {
293         return encode_number(signal, float(value), send);
294 }
295 /// @brief Encode a float into an integer, fit for a CAN signal's bitfield.
296 ///
297 /// This is a shortcut for encodeDynamicField(CanSignal*, openxc_DynamicField*,
298 /// bool*) that takes care of creating the DynamicField object for you with the
299 /// float value.
300 ///
301 /// @param[in] signal  - The CAN signal to encode this value for.
302 /// @param[in] value - The float value to encode.
303 /// @param[out] send - This output argument will always be set to false, so the caller will
304 ///      know not to publish this value to the pipeline.
305 ///
306 /// @return Returns the encoded integer. If 'send' is changed to false, the field could
307 /// not be encoded and the return value is undefined.
308 ///
309 uint64_t encoder_t::encode_number(const signal_t& signal, float value, bool* send)
310 {
311         return float_to_fixed_point(value, signal.get_factor(), signal.get_offset());
312 }
313
314 /// @brief Encode a string into an integer, fit for a CAN signal's bitfield.
315 ///
316 /// Be aware that the behavior is undefined if there are multiple values assigned
317 /// to a single state. See https://github.com/openxc/vi-firmware/issues/185.
318 ///
319 /// This is a shortcut for encodeDynamicField(CanSignal*, openxc_DynamicField*,
320 /// bool*) that takes care of creating the DynamicField object for you with the
321 /// string state value.
322 ///
323 /// @param[in] signal  - The details of the signal that contains the state mapping.
324 /// @param[in] value - The string state value to encode.
325 /// @param[out] send - An output argument that will be set to false if the value should
326 ///     not be sent for any reason.
327 ///
328 /// @return Returns the encoded integer. If 'send' is changed to false, the field could
329 /// not be encoded and the return value is undefined.
330 ///
331 uint64_t encoder_t::encode_state(const signal_t& signal, const std::string& state, bool* send)
332 {
333         uint64_t value = 0;
334         if(state == "")
335         {
336                 AFB_DEBUG("Can't write state of "" -- not sending");
337                 *send = false;
338         }
339         else
340         {
341                 uint64_t signal_state = signal.get_states(state);
342                 if(signal_state != -1) {
343                         value = signal_state;
344                 } else {
345                         AFB_DEBUG("Couldn't find a valid signal state for %s", state.c_str());
346                         *send = false;
347                 }
348         }
349         return value;
350 }
351
352 /// @brief Parse a signal from a CAN message and apply any required
353 /// transforations to get a human readable value.
354 ///
355 /// If the signal_t has a non-NULL 'decoder' field, the raw CAN signal value
356 /// will be passed to the decoder before returning.
357 ///
358 /// @param[in] signal - The details of the signal to decode and forward.
359 /// @param[in] value - The numerical value that will be converted to a boolean.
360 /// @param[out] send - An output parameter that will be flipped to false if the value could
361 ///      not be decoded.
362 ///
363 /// @return The decoder returns an openxc_DynamicField, which may contain a number,
364 /// string or boolean. If 'send' is false, the return value is undefined.
365 ///
366 uint64_t encoder_t::encode_DynamicField( signal_t& signal, const openxc_DynamicField& field, bool* send)
367 {
368         uint64_t value = 0;
369         switch(field.type) {
370                 case openxc_DynamicField_Type_STRING:
371                         value = encode_state(signal, field.string_value, send);
372                         break;
373                 case openxc_DynamicField_Type_NUM:
374                         value = encode_number(signal, (float)field.numeric_value, send);
375                         break;
376                 case openxc_DynamicField_Type_BOOL:
377                         value = encode_boolean(signal, field.boolean_value, send);
378                         break;
379                 default:
380                         AFB_DEBUG("Dynamic field didn't have a value, can't encode");
381                         *send = false;
382                         break;
383         }
384         return value;
385 }