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