Update flag FRAME_LAYOUT_IS_BIGENDIAN to BYTE_FRAME_IS_BIG_ENDIAN
[apps/agl-service-can-low-level.git] / low-can-binding / can / can-decoder.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-decoder.hpp"
19 #include <climits>
20
21 #include "canutil/read.h"
22 #include "../utils/openxc-utils.hpp"
23 #include "message-definition.hpp"
24 #include "../binding/low-can-hat.hpp"
25 #include "../utils/converter.hpp"
26
27 /// @brief Handle sign of the signal according to several decoding methods
28 ///
29 /// @param[in] signal - The signal
30 /// @param[in] data_signal - The data of the signal
31 /// @param[in] new_end_bit - The last bit of in the last byte of the data (data_signal[0])
32 /// @param[in] can_data - The whole can data (needed for SIGN BIT EXTERN)
33 ///
34 /// @return Returns the sign of the data
35 ///
36 int decoder_t::handle_sign(const signal_t& signal, std::vector<uint8_t>& data_signal, uint8_t new_end_bit, const std::vector<uint8_t>& can_data)
37 {
38         uint8_t data_byte = 0;
39         uint8_t mask = 0;
40         int end_bit = 0;
41
42         if(signal.get_sign() == sign_t::UNSIGNED)
43                 return 1;
44         else if(signal.get_sign() == sign_t::SIGN_BIT_EXTERN) {
45                 end_bit = signal.get_bit_sign_position() % CHAR_BIT;
46                 mask = static_cast<uint8_t>((1 << (end_bit + 1)) - 1);
47                 data_byte = can_data[signal.get_bit_sign_position() / CHAR_BIT] & mask;
48         }
49         else {
50                 end_bit = new_end_bit;
51                 mask = static_cast<uint8_t>((1 << (end_bit + 1)) - 1);
52                 data_byte = data_signal[0] & mask;
53         }
54
55         //if negative: decode with right method
56         if(data_byte  >> end_bit) {
57                 switch(signal.get_sign())
58                 {
59                         //remove the sign bit to get the absolute value
60                         case sign_t::SIGN_BIT:
61                                 data_signal[0] = static_cast<uint8_t>(data_signal[0] & (mask >> 1));
62                                 break;
63                         //same method twos complement = ones complement + 1
64                         case sign_t::ONES_COMPLEMENT:
65                         case sign_t::TWOS_COMPLEMENT:
66                                 //complement only until end_bit
67                                 data_signal[0] = ((data_signal[0] ^ mask) & mask);
68                                 if(data_signal.size() > 1)
69                                         for(int i=1; i < data_signal.size(); i++)
70                                                 data_signal[i] = data_signal[i] ^ 0xFF;
71                                 if(signal.get_sign() == sign_t::TWOS_COMPLEMENT)
72                                         data_signal[data_signal.size() - 1] = static_cast<uint8_t>(data_signal[data_signal.size() - 1] + 1);
73                                 break;
74                         case sign_t::SIGN_BIT_EXTERN:
75                                 break;
76                         default:
77                                 AFB_ERROR("Not a valid sign entry %d, considering the value as unsigned", signal.get_sign());
78                                 break;
79                 }
80                 return -1;
81         }
82         return 1;
83 }
84
85 /// @brief Parses the signal's bitfield from the given data and returns the raw
86 /// value.
87 ///
88 /// @param[in] signal - The signal to be parsed from the data.
89 /// @param[in] message - message_t to parse
90 ///
91 /// @return Returns the raw value of the signal parsed as a bitfield from the given byte
92 /// array.
93 ///
94 float decoder_t::parse_signal_bitfield(signal_t& signal, std::shared_ptr<message_t> message)
95 {
96         int sign;
97         std::vector<uint8_t> data;
98         std::vector<uint8_t> data_signal;
99         uint8_t bit_size = (uint8_t) signal.get_bit_size();
100         uint32_t bit_position = signal.get_bit_position();
101
102         int new_start_byte = 0;
103         int new_end_byte = 0;
104         uint8_t new_start_bit = 0;
105         uint8_t new_end_bit = 0;
106
107         if(signal.get_message()->get_flags() & CONTINENTAL_BIT_POSITION)
108                 bit_position = converter_t::continental_bit_position_mess(message->get_length(),
109                                                               signal.get_bit_position(),
110                                                               bit_size);
111         if(signal.get_message()->get_flags() & BIT_POSITION_REVERSED)
112                 bit_position = converter_t::bit_position_swap(message->get_length(),
113                                                               signal.get_bit_position(),
114                                                               bit_size);
115         if(signal.get_message()->get_flags() & BYTE_FRAME_IS_BIG_ENDIAN)
116                 message->frame_swap();
117
118         data = message->get_data_vector();
119         converter_t::signal_to_bits_bytes(bit_position, bit_size, new_start_byte, new_end_byte, new_start_bit, new_end_bit);
120
121         for(int i=new_start_byte;i<=new_end_byte;i++)
122                 data_signal.push_back(data[i]);
123
124         sign = handle_sign(signal, data_signal, new_end_bit, data);
125
126         if(data_signal.size() > 65535)
127                 AFB_ERROR("Too long data signal %s", signal.get_name().c_str());
128
129         return static_cast<float>(sign) * bitfield_parse_float(data_signal.data(), (uint16_t) data_signal.size(),
130                         new_start_bit, bit_size, signal.get_factor(),
131                         signal.get_offset());
132 }
133
134
135 /// @brief Decode and return string bytes (hex) for a CAN signal's.
136 ///
137 /// This is an implementation of the Signal type signature, and can be
138 /// used directly in the signal_t.decoder field.
139 ///
140 /// @param[in] signal  - The details of the signal.
141 /// @param[in] message - The message with data to decode.
142 /// @param[out] send - An output argument that will be set to false if the value should
143 ///     not be sent for any reason.
144 ///
145 /// @return Returns a DynamicField with a string value of bytes (hex)
146 ///
147 openxc_DynamicField decoder_t::decode_bytes(signal_t& signal, std::shared_ptr<message_t> message, bool* send)
148 {
149         int i=0;
150         openxc_DynamicField decoded_value;
151         std::vector<uint8_t> data = message->get_data_vector();
152         uint32_t length = message->get_length();
153         uint32_t bit_position = signal.get_bit_position();
154         uint32_t bit_size = signal.get_bit_size();
155
156         std::vector<uint8_t> new_data = std::vector<uint8_t>();
157         new_data.reserve((bit_size / CHAR_BIT) + 1);
158
159         int new_start_byte = 0;
160         int new_end_byte = 0;
161         uint8_t new_start_bit = 0;
162         uint8_t new_end_bit = 0;
163
164         converter_t::signal_to_bits_bytes(bit_position, bit_size, new_start_byte, new_end_byte, new_start_bit, new_end_bit);
165
166         if(new_end_byte >= length)
167                 new_end_byte = length-1;
168
169         if(new_start_byte >= length)
170         {
171                 AFB_ERROR("Error in signal's description");
172                 return decoded_value;
173         }
174
175         uint8_t mask_first_v = static_cast<uint8_t>(0xFF << new_start_bit);
176         uint8_t mask_last_v = static_cast<uint8_t>(0xFF >> (7 - new_end_bit));
177
178         if(new_start_byte == new_end_byte)
179         {
180                 data[new_start_byte] = data[new_start_byte] & (mask_first_v & mask_last_v);
181         }
182         else
183         {
184                 data[new_start_byte] = data[new_start_byte] & mask_first_v;
185                 data[new_end_byte] = data[new_end_byte] & mask_last_v;
186         }
187
188         for(i=new_start_byte ; i <= new_end_byte ; i++)
189                 new_data.push_back(data[i]);
190
191         decoded_value = build_DynamicField(new_data);
192
193         return decoded_value;
194 }
195
196
197 /// @brief Decode and return string bytes (hex) for a CAN signal's.
198 ///
199 /// This is an implementation of the Signal type signature, and can be
200 /// used directly in the signal_t.decoder field.
201 ///
202 /// @param[in] signal  - The details of the signal.
203 /// @param[in] message - The message with data to decode.
204 /// @param[out] send - An output argument that will be set to false if the value should
205 ///     not be sent for any reason.
206 ///
207 /// @return Returns a DynamicField with a string value of bytes (hex)
208 ///
209 openxc_DynamicField decoder_t::decode_ascii(signal_t& signal, std::shared_ptr<message_t> message, bool* send)
210 {
211         std::string ret_s = "";
212         openxc_DynamicField openxc_bytes = decode_bytes(signal,message,send);
213         if(!openxc_bytes.has_bytes_value)
214                 AFB_ERROR("Error no bytes value to translate to ascii");
215         ret_s = converter_t::to_ascii(openxc_bytes.bytes_value,openxc_bytes.length_array);
216         openxc_DynamicField ret = build_DynamicField(ret_s);
217         return ret;
218 }
219
220 //edit
221 openxc_DynamicField decoder_t::decode_date(signal_t& signal, std::shared_ptr<message_t> message, bool* send)
222 {
223         float value = decoder_t::parse_signal_bitfield(signal, message);
224         AFB_DEBUG("Decoded message from parse_signal_bitfield: %f", value);
225         openxc_DynamicField decoded_value = build_DynamicField(value);
226
227         // Don't send if they is no changes
228         if ((signal.get_last_value() == value && !signal.get_send_same()) || !*send )
229                 *send = false;
230         signal.set_last_value(value);
231
232         return decoded_value;
233 }
234
235 //edit
236 openxc_DynamicField decoder_t::decode_time(signal_t& signal, std::shared_ptr<message_t> message, bool* send)
237 {
238         float value = decoder_t::parse_signal_bitfield(signal, message);
239         AFB_DEBUG("Decoded message from parse_signal_bitfield: %f", value);
240         openxc_DynamicField decoded_value = build_DynamicField(value);
241
242         // Don't send if they is no changes
243         *send = (signal.get_last_value() == value && !signal.get_send_same()) || !*send ? false : true;
244         signal.set_last_value(value);
245
246         return decoded_value;
247 }
248
249
250 /// @brief Wraps a raw CAN signal value in a DynamicField without modification.
251 ///
252 /// This is an implementation of the Signal type signature, and can be
253 /// used directly in the signal_t.decoder field.
254 ///
255 /// @param[in] signal - The details of the signal that contains the state mapping.
256 /// @param[in] message - The message with data to decode.
257 /// @param[out] send - An output argument that will be set to false if the value should
258 ///     not be sent for any reason.
259 ///
260 /// @return Returns a DynamicField with the original, unmodified raw CAN signal value as
261 /// its numeric value. The 'send' argument will not be modified as this decoder
262 /// always succeeds.
263 ///
264 openxc_DynamicField decoder_t::decode_noop(signal_t& signal, std::shared_ptr<message_t> message, bool* send)
265 {
266         float value = decoder_t::parse_signal_bitfield(signal, message);
267         AFB_DEBUG("Decoded message from parse_signal_bitfield: %f", value);
268         openxc_DynamicField decoded_value = build_DynamicField(value);
269
270         // Don't send if they is no changes
271         if ((signal.get_last_value() == value && !signal.get_send_same()) || !*send )
272                 *send = false;
273         signal.set_last_value(value);
274
275         return decoded_value;
276 }
277 /// @brief Coerces a numerical value to a boolean.
278 ///
279 /// This is an implementation of the Signal type signature, and can be
280 /// used directly in the signal_t.decoder field.
281 ///
282 /// @param[in] signal  - The details of the signal that contains the state mapping.
283 /// @param[in] message - The message with data to decode.
284 /// @param[out] send - An output argument that will be set to false if the value should
285 ///     not be sent for any reason.
286 ///
287 /// @return Returns a DynamicField with a boolean value of false if the raw signal value
288 /// is 0.0, otherwise true. The 'send' argument will not be modified as this
289 /// decoder always succeeds.
290 ///
291 openxc_DynamicField decoder_t::decode_boolean(signal_t& signal, std::shared_ptr<message_t> message, bool* send)
292 {
293         float value = decoder_t::parse_signal_bitfield(signal, message);
294         AFB_DEBUG("Decoded message from parse_signal_bitfield: %f", value);
295         openxc_DynamicField decoded_value = build_DynamicField(value == 0.0 ? false : true);
296
297         // Don't send if they is no changes
298         if ((signal.get_last_value() == value && !signal.get_send_same()) || !*send )
299                 *send = false;
300
301         signal.set_last_value(value);
302
303
304         return decoded_value;
305 }
306 /// @brief Update the metadata for a signal and the newly received value.
307 ///
308 /// This is an implementation of the Signal type signature, and can be
309 /// used directly in the signal_t.decoder field.
310 ///
311 /// This function always flips 'send' to false.
312 ///
313 /// @param[in] signal  - The details of the signal that contains the state mapping.
314 /// @param[in] message - The message with data to decode.
315 /// @param[out] send - This output argument will always be set to false, so the caller will
316 ///      know not to publish this value to the pipeline.
317 ///
318 /// @return Return value is undefined.
319 ///
320 openxc_DynamicField decoder_t::decode_ignore(signal_t& signal, std::shared_ptr<message_t> message, bool* send)
321 {
322         float value = decoder_t::parse_signal_bitfield(signal, message);
323         if(send)
324           *send = false;
325
326         signal.set_last_value(value);
327         openxc_DynamicField decoded_value;
328
329         return decoded_value;
330 }
331
332 /// @brief Find and return the corresponding string state for a CAN signal's
333 /// raw integer value.
334 ///
335 /// This is an implementation of the Signal type signature, and can be
336 /// used directly in the signal_t.decoder field.
337 ///
338 /// @param[in] signal  - The details of the signal that contains the state mapping.
339 /// @param[in] message - The message with data to decode.
340 /// @param[out] send - An output argument that will be set to false if the value should
341 ///     not be sent for any reason.
342 ///
343 /// @return Returns a DynamicField with a string value if a matching state is found in
344 /// the signal. If an equivalent isn't found, send is sent to false and the
345 /// return value is undefined.
346 ///
347 openxc_DynamicField decoder_t::decode_state(signal_t& signal, std::shared_ptr<message_t> message, bool* send)
348 {
349         float value = decoder_t::parse_signal_bitfield(signal, message);
350         AFB_DEBUG("Decoded message from parse_signal_bitfield: %f", value);
351         const std::string signal_state = signal.get_states((uint8_t)value);
352         openxc_DynamicField decoded_value = build_DynamicField(signal_state);
353         if(signal_state.size() <= 0)
354         {
355                 *send = false;
356                 AFB_ERROR("No state found with index: %d", (int)value);
357         }
358
359         // Don't send if they is no changes
360         if ((signal.get_last_value() == value && !signal.get_send_same()) || !*send )
361                 *send = false;
362         signal.set_last_value(value);
363
364
365         return decoded_value;
366 }
367
368
369 /// @brief Parse a signal from a CAN message, apply any required transforations
370 ///      to get a human readable value and public the result to the pipeline.
371 ///
372 /// If the signal_t has a non-NULL 'decoder' field, the raw CAN signal value
373 /// will be passed to the decoder before publishing.
374 ///
375 /// @param[in] signal - The details of the signal to decode and forward.
376 /// @param[in] message - The message with data to decode.
377 /// @param[out] send - An output parameter that will be flipped to false if the value could
378 ///      not be decoded.
379 ///
380 /// The decoder returns an openxc_DynamicField, which may contain a number,
381 /// string or boolean.
382 ///
383 openxc_DynamicField decoder_t::translate_signal(signal_t& signal, std::shared_ptr<message_t> message, bool* send)
384 {
385         // Must call the decoders every time, regardless of if we are going to
386         // decide to send the signal or not.
387         openxc_DynamicField decoded_value = decoder_t::decode_signal(signal,
388                         message, send);
389
390         signal.set_received(true);
391         signal.set_timestamp(message->get_timestamp());
392         signal.get_message()->set_last_value(message);
393         return decoded_value;
394 }
395
396 /// @brief Parse a signal from a CAN message and apply any required
397 /// transforations to get a human readable value.
398 ///
399 /// If the signal_t has a non-NULL 'decoder' field, the raw CAN signal value
400 /// will be passed to the decoder before returning.
401 ///
402 /// @param[in] signal - The details of the signal to decode and forward.
403 /// @param[in] message - The message with data to decode.
404 /// @param[out] send - An output parameter that will be flipped to false if the value could
405 ///      not be decoded.
406 ///
407 /// @return The decoder returns an openxc_DynamicField, which may contain a number,
408 /// string or boolean. If 'send' is false, the return value is undefined.
409 ///
410 openxc_DynamicField decoder_t::decode_signal( signal_t& signal, std::shared_ptr<message_t> message, bool* send)
411 {
412         signal_decoder decoder = signal.get_decoder() == nullptr ?
413                                                         decode_noop : signal.get_decoder();
414
415         openxc_DynamicField decoded_value = decoder(signal,
416                         message, send);
417         return decoded_value;
418 }
419
420 ///
421 /// @brief Decode the payload of an OBD-II PID.
422 ///
423 /// This function matches the type signature for a DiagnosticResponse, so
424 /// it can be used as the decoder for a DiagnosticRequest. It returns the decoded
425 /// value of the PID, using the standard formulas (see
426 /// http://en.wikipedia.org/wiki/OBD-II_PIDs#Mode_01).
427 ///
428 /// @param[in] response - the received DiagnosticResponse (the data is in response.payload,
429 ///  a byte array). This is most often used when the byte order is
430 ///  signiticant, i.e. with many OBD-II PID formulas.
431 /// @param[in] parsed_payload - the entire payload of the response parsed as an int.
432 ///
433 /// @return Float decoded value.
434 ///
435 float decoder_t::decode_obd2_response(const DiagnosticResponse* response, float parsed_payload)
436 {
437         return diagnostic_decode_obd2_pid(response);
438 }