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