ae10cd980ae8c2b678e5c48155d45835148d7f94
[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                                         }
72                                 }
73                                 if(signal.get_sign() == sign_t::TWOS_COMPLEMENT)
74                                         data_signal[data_signal.size() - 1] = static_cast<uint8_t>(data_signal[data_signal.size() - 1] + 1);
75                                 break;
76                         case sign_t::SIGN_BIT_EXTERN:
77                                 break;
78                         default:
79                                 AFB_ERROR("Not a valid sign entry %d, considering the value as unsigned", signal.get_sign());
80                                 break;
81                 }
82                 return -1;
83         }
84         return 1;
85 }
86
87 /// @brief Parses the signal's bitfield from the given data and returns the raw
88 /// value.
89 ///
90 /// @param[in] signal - The signal to be parsed from the data.
91 /// @param[in] message - message_t to parse
92 ///
93 /// @return Returns the raw value of the signal parsed as a bitfield from the given byte
94 /// array.
95 ///
96 float decoder_t::parse_signal_bitfield(signal_t& signal, std::shared_ptr<message_t> message)
97 {
98         int sign;
99         std::vector<uint8_t> data;
100         std::vector<uint8_t> data_signal;
101         uint8_t bit_size = (uint8_t) signal.get_bit_size();
102         uint32_t bit_position = signal.get_bit_position();
103
104         int new_start_byte = 0;
105         int new_end_byte = 0;
106         uint8_t new_start_bit = 0;
107         uint8_t new_end_bit = 0;
108
109         if(signal.get_message()->frame_layout_is_bigendian())
110         {
111                 bit_position = converter_t::bit_position_swap(message->get_length(),
112                                                               signal.get_bit_position(),
113                                                               bit_size);
114                 message->frame_swap();
115         }
116
117         data = message->get_data_vector();
118         converter_t::signal_to_bits_bytes(bit_position, bit_size, new_start_byte, new_end_byte, new_start_bit, new_end_bit);
119
120         for(int i=new_start_byte;i<=new_end_byte;i++)
121                 data_signal.push_back(data[i]);
122
123         sign = handle_sign(signal, data_signal, new_end_bit, data);
124
125         if(data_signal.size() > 65535)
126                 AFB_ERROR("Too long data signal %s", signal.get_name().c_str());
127
128         return static_cast<float>(sign) * bitfield_parse_float(data_signal.data(), (uint16_t) data_signal.size(),
129                         new_start_bit, bit_size, signal.get_factor(),
130                         signal.get_offset());
131 }
132
133
134 /// @brief Decode and return string bytes (hex) for a CAN signal's.
135 ///
136 /// This is an implementation of the Signal type signature, and can be
137 /// used directly in the signal_t.decoder field.
138 ///
139 /// @param[in] signal  - The details of the signal.
140 /// @param[in] message - The message with data to decode.
141 /// @param[out] send - An output argument that will be set to false if the value should
142 ///     not be sent for any reason.
143 ///
144 /// @return Returns a DynamicField with a string value of bytes (hex)
145 ///
146 openxc_DynamicField decoder_t::decode_bytes(signal_t& signal, std::shared_ptr<message_t> message, bool* send)
147 {
148         int i=0;
149         openxc_DynamicField decoded_value;
150         std::vector<uint8_t> data = message->get_data_vector();
151         uint32_t length = message->get_length();
152         uint32_t bit_position = signal.get_bit_position();
153         uint32_t bit_size = signal.get_bit_size();
154
155         std::vector<uint8_t> new_data = std::vector<uint8_t>();
156         new_data.reserve((bit_size / CHAR_BIT) + 1);
157
158         int new_start_byte = 0;
159         int new_end_byte = 0;
160         uint8_t new_start_bit = 0;
161         uint8_t new_end_bit = 0;
162
163         converter_t::signal_to_bits_bytes(bit_position, bit_size, new_start_byte, new_end_byte, new_start_bit, new_end_bit);
164
165         if(new_end_byte >= length)
166                 new_end_byte = length-1;
167
168         if(new_start_byte >= length)
169         {
170                 AFB_ERROR("Error in signal's description");
171                 return decoded_value;
172         }
173
174         uint8_t mask_first_v = static_cast<uint8_t>(0xFF << new_start_bit);
175         uint8_t mask_last_v = static_cast<uint8_t>(0xFF >> (7 - new_end_bit));
176
177         if(new_start_byte == new_end_byte)
178         {
179                 data[new_start_byte] = data[new_start_byte] & (mask_first_v & mask_last_v);
180         }
181         else
182         {
183                 data[new_start_byte] = data[new_start_byte] & mask_first_v;
184                 data[new_end_byte] = data[new_end_byte] & mask_last_v;
185         }
186
187         for(i=new_start_byte ; i <= new_end_byte ; i++)
188                 new_data.push_back(data[i]);
189
190         decoded_value = build_DynamicField(new_data);
191
192         return decoded_value;
193 }
194
195 /// @brief Wraps a raw CAN signal value in a DynamicField without modification.
196 ///
197 /// This is an implementation of the Signal type signature, and can be
198 /// used directly in the signal_t.decoder field.
199 ///
200 /// @param[in] signal - The details of the signal that contains the state mapping.
201 /// @param[in] message - The message with data to decode.
202 /// @param[out] send - An output argument that will be set to false if the value should
203 ///     not be sent for any reason.
204 ///
205 /// @return Returns a DynamicField with the original, unmodified raw CAN signal value as
206 /// its numeric value. The 'send' argument will not be modified as this decoder
207 /// always succeeds.
208 ///
209 openxc_DynamicField decoder_t::decode_noop(signal_t& signal, std::shared_ptr<message_t> message, bool* send)
210 {
211         float value = decoder_t::parse_signal_bitfield(signal, message);
212         AFB_DEBUG("Decoded message from parse_signal_bitfield: %f", value);
213         openxc_DynamicField decoded_value = build_DynamicField(value);
214
215         // Don't send if they is no changes
216         if ((signal.get_last_value() == value && !signal.get_send_same()) || !*send )
217         {
218                 *send = false;
219         }
220         signal.set_last_value(value);
221
222         return decoded_value;
223 }
224 /// @brief Coerces a numerical value to a boolean.
225 ///
226 /// This is an implementation of the Signal type signature, and can be
227 /// used directly in the signal_t.decoder field.
228 ///
229 /// @param[in] signal  - The details of the signal that contains the state mapping.
230 /// @param[in] message - The message with data to decode.
231 /// @param[out] send - An output argument that will be set to false if the value should
232 ///     not be sent for any reason.
233 ///
234 /// @return Returns a DynamicField with a boolean value of false if the raw signal value
235 /// is 0.0, otherwise true. The 'send' argument will not be modified as this
236 /// decoder always succeeds.
237 ///
238 openxc_DynamicField decoder_t::decode_boolean(signal_t& signal, std::shared_ptr<message_t> message, bool* send)
239 {
240         float value = decoder_t::parse_signal_bitfield(signal, message);
241         AFB_DEBUG("Decoded message from parse_signal_bitfield: %f", value);
242         openxc_DynamicField decoded_value = build_DynamicField(value == 0.0 ? false : true);
243
244         // Don't send if they is no changes
245         if ((signal.get_last_value() == value && !signal.get_send_same()) || !*send )
246                 *send = false;
247
248         signal.set_last_value(value);
249
250
251         return decoded_value;
252 }
253 /// @brief Update the metadata for a signal and the newly received value.
254 ///
255 /// This is an implementation of the Signal type signature, and can be
256 /// used directly in the signal_t.decoder field.
257 ///
258 /// This function always flips 'send' to false.
259 ///
260 /// @param[in] signal  - The details of the signal that contains the state mapping.
261 /// @param[in] message - The message with data to decode.
262 /// @param[out] send - This output argument will always be set to false, so the caller will
263 ///      know not to publish this value to the pipeline.
264 ///
265 /// @return Return value is undefined.
266 ///
267 openxc_DynamicField decoder_t::decode_ignore(signal_t& signal, std::shared_ptr<message_t> message, bool* send)
268 {
269         float value = decoder_t::parse_signal_bitfield(signal, message);
270         if(send)
271           *send = false;
272
273         signal.set_last_value(value);
274         openxc_DynamicField decoded_value;
275
276         return decoded_value;
277 }
278
279 /// @brief Find and return the corresponding string state for a CAN signal's
280 /// raw integer value.
281 ///
282 /// This is an implementation of the Signal type signature, and can be
283 /// used directly in the signal_t.decoder field.
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 - An output argument that will be set to false if the value should
288 ///     not be sent for any reason.
289 ///
290 /// @return Returns a DynamicField with a string value if a matching state is found in
291 /// the signal. If an equivalent isn't found, send is sent to false and the
292 /// return value is undefined.
293 ///
294 openxc_DynamicField decoder_t::decode_state(signal_t& signal, std::shared_ptr<message_t> message, bool* send)
295 {
296         float value = decoder_t::parse_signal_bitfield(signal, message);
297         AFB_DEBUG("Decoded message from parse_signal_bitfield: %f", value);
298         const std::string signal_state = signal.get_states((uint8_t)value);
299         openxc_DynamicField decoded_value = build_DynamicField(signal_state);
300         if(signal_state.size() <= 0)
301         {
302                 *send = false;
303                 AFB_ERROR("No state found with index: %d", (int)value);
304         }
305
306         // Don't send if they is no changes
307         if ((signal.get_last_value() == value && !signal.get_send_same()) || !*send )
308         {
309                 *send = false;
310         }
311         signal.set_last_value(value);
312
313
314         return decoded_value;
315 }
316
317
318 /// @brief Parse a signal from a CAN message, apply any required transforations
319 ///      to get a human readable value and public the result to the pipeline.
320 ///
321 /// If the signal_t has a non-NULL 'decoder' field, the raw CAN signal value
322 /// will be passed to the decoder before publishing.
323 ///
324 /// @param[in] signal - The details of the signal to decode and forward.
325 /// @param[in] message - The message with data to decode.
326 /// @param[out] send - An output parameter that will be flipped to false if the value could
327 ///      not be decoded.
328 ///
329 /// The decoder returns an openxc_DynamicField, which may contain a number,
330 /// string or boolean.
331 ///
332 openxc_DynamicField decoder_t::translate_signal(signal_t& signal, std::shared_ptr<message_t> message, bool* send)
333 {
334         // Must call the decoders every time, regardless of if we are going to
335         // decide to send the signal or not.
336         openxc_DynamicField decoded_value = decoder_t::decode_signal(signal,
337                         message, send);
338
339         signal.set_received(true);
340         signal.set_timestamp(message->get_timestamp());
341         signal.get_message()->set_last_value(message);
342         return decoded_value;
343 }
344
345 /// @brief Parse a signal from a CAN message and apply any required
346 /// transforations to get a human readable value.
347 ///
348 /// If the signal_t has a non-NULL 'decoder' field, the raw CAN signal value
349 /// will be passed to the decoder before returning.
350 ///
351 /// @param[in] signal - The details of the signal to decode and forward.
352 /// @param[in] message - The message with data to decode.
353 /// @param[out] send - An output parameter that will be flipped to false if the value could
354 ///      not be decoded.
355 ///
356 /// @return The decoder returns an openxc_DynamicField, which may contain a number,
357 /// string or boolean. If 'send' is false, the return value is undefined.
358 ///
359 openxc_DynamicField decoder_t::decode_signal( signal_t& signal, std::shared_ptr<message_t> message, bool* send)
360 {
361         signal_decoder decoder = signal.get_decoder() == nullptr ?
362                                                         decode_noop : signal.get_decoder();
363
364         openxc_DynamicField decoded_value = decoder(signal,
365                         message, send);
366         return decoded_value;
367 }
368
369 ///
370 /// @brief Decode the payload of an OBD-II PID.
371 ///
372 /// This function matches the type signature for a DiagnosticResponse, so
373 /// it can be used as the decoder for a DiagnosticRequest. It returns the decoded
374 /// value of the PID, using the standard formulas (see
375 /// http://en.wikipedia.org/wiki/OBD-II_PIDs#Mode_01).
376 ///
377 /// @param[in] response - the received DiagnosticResponse (the data is in response.payload,
378 ///  a byte array). This is most often used when the byte order is
379 ///  signiticant, i.e. with many OBD-II PID formulas.
380 /// @param[in] parsed_payload - the entire payload of the response parsed as an int.
381 ///
382 /// @return Float decoded value.
383 ///
384 float decoder_t::decode_obd2_response(const DiagnosticResponse* response, float parsed_payload)
385 {
386         return diagnostic_decode_obd2_pid(response);
387 }